Django JWT Auth和Vue:如何检查用户是否登录Vue



我的后端在Django,前端在Vue。

用户在Vue中执行登录,并通过POST请求将凭据发送到Django JWT登录端点。此终结点返回在localStorage中设置的令牌。

然后我想在Vue中检查用户是否登录。因此,Django中存在另一个端点。然而,它总是返回";匿名用户";。我不知道如何设置这张支票。

Django:

我的设置.py

JWT_AUTH = {
'JWT_ALLOW_REFRESH': True,
'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1),
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
}

我的网址.py

path('check-auth', views.check_if_logged_in, name="check-auth"), # check auth
path('auth/obtain_token', obtain_jwt_token), # obtain token
path('auth/refresh_token', refresh_jwt_token),

我的观点.py

# Login Check
@csrf_exempt
def check_if_logged_in(request):
authentication_class = (JSONWebTokenAuthentication,)  
permission_classes = (IsAuthenticated,)
print(request.user) # returns AnonymUser
check = None
if request.user.is_authenticated:
check = True
else:
check = False
print(check) # returns False
return HttpResponse(f"<html><body>{check}</body></html>")

Vue

获取令牌函数

obtainToken(){
var that = this;
fetch(this.endpoints.obtainJWT, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: that.django.username,
password: that.django.password
})
}).then(response => response.json()
).then(function(response) { 
console.log('auth', response); # get token
that.updateToken(response.token); # update localStorage
that.checkAuthData(); #check auth
});
},

checkAuth函数

checkAuthData: function() {
var that = this;
fetch('http://localhost:8000/check-auth', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
token: this.jwt # send token
})
}).then(response => response.json()
).then(function(response) { 
console.log('check', response); 
});
},

您应该不在主体中包含令牌,而是在标头中包含:

headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.jwt
},

此外,请确保在REST_FRAMEWORKDEFAULT_AUTHENTICATION_CLASSES中的Django设置中包含JWT身份验证:

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
...
'rest_framework_simplejwt.authentication.JWTAuthentication',
]
}

最新更新