django - Django JWT Auth 和 Vue:如何检查用户是否登录 Vue?
问题描述
我在 Django 中有我的后端,在 Vue 中有我的前端。
用户在 Vue 中执行登录,并通过 POST 请求将凭据发送到 Django JWT 登录端点。此端点返回一个在 localStorage 中设置的令牌。
然后我想在 Vue 中检查用户是否已登录。为此,Django 中存在另一个端点。但是,它总是返回“AnonymUser”。我不知道如何设置此检查。
姜戈:
我的设置.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
},
另外,请确保在您的 Django 设置中REST_FRAMEWORK
DEFAULT_AUTHENTICATION_CLASSES
包含 JWT 身份验证:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
...
'rest_framework_simplejwt.authentication.JWTAuthentication',
]
}
推荐阅读
- json - JIRA API POST jql 搜索
- sql - Oracle SQl Dev,显示 id、firstname、surname 和 users 文件数
- c++ - 使用字符数组的字符串输入问题c ++
- javascript - tampermonkey 中带有 GM_xmlhttpRequest 的简单脚本每秒运行一次 - 内存泄漏
- python - Neovim 在运行 input() 时抛出错误,在 Vim 中运行正常
- android - 使用依赖项构建 AAR
- android - 通过 UIautomator 查找元素
- c# - 在 Simple Injector 中注册期间设置收集项目的生活方式
- python - 如何在 Python3 中修复我的“添加函数使用按位运算符”代码?
- unity3d - 盒子对撞机彼此相邻错误