一般情況下,進入到web網站主頁都需要進行token或者其它驗證,不能在沒有登錄的情況下可以查看主頁的內容,在用戶輸入用戶名密碼后,進行校驗成功,后台會返回一個token,用於用於下次訪問主頁或其它頁面進行用戶認證,一旦認證成功就可以訪問了。
1、用戶獲取token
用戶向后台API發送用戶名和密碼進行校驗以及獲取token。
methods: { loginSubmit(formName) { this.$refs[formName].validate(async (valid) => { if (valid) { const res = await this.$http.post('login', this.form); const {data, meta: {message, code}} = res.data; if (code === 2000) { //獲取token,將token值存儲在localStorage localStorage.setItem('token', data.token); //驗證成功后直接跳轉到主頁 this.$router.push({name: 'home'}); //登陸成功提示 this.$message.success(message) } else { this.$message.warning(message) } } else { this.$message.warning("用戶名或密碼不能為空") } }); } },
2、后台進行驗證
class LoginView(APIView): authentication_classes = [] # 登陸頁面免認證,其余的已經全局配置 def post(self, request, *args, **kwargs): ret = { "data": {}, "meta": { "code": 2001, "message": "用戶名或密碼錯誤" } } user_obj = json.loads(str(request._request.body, encoding='utf8')) username = user_obj.get('username') password = user_obj.get('password') if username and password: obj = UserInfo.objects.filter( username=username, password=password).first() if obj: token = get_md5(username) # 自動去數據庫檢查,如果沒有就創建,否則更新token UserToken.objects.update_or_create(user=obj, defaults={'token': token}) ret["data"]["username"] = username ret["data"]["password"] = password ret["data"]["token"] = token ret["meta"]["code"] = 2000 ret["meta"]["message"] = "登陸成功" else: pass else: pass return HttpResponse(json.dumps(ret, ensure_ascii=False))