首页 > 解决方案 > 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); 
                    });
                },

标签: djangovue.jsdjango-rest-frameworkjwt

解决方案


您不应该在正文中包含令牌,而是在标题中包含:

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',
    ]
}

推荐阅读