Django JWT Auth and Vue: How to check if user is logged in in Vue?

Viewed 782

I have my backend in Django and front in Vue.

A user performes login in Vue and via a POST request the creds are sent to a Django JWT login endpoint. This endpoint returns a token which is set in localStorage.

Then I want to check in Vue that the user is logged in. For that another endpoint in Django exists. However, it always returns "AnonymUser". I cannot get how to set this check.

Django:

My settings.py

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

My urls.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),

My views.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 function

                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 function

                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); 
                    });
                },

1 Answers

You should include token not in the body, but in the header instead:

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

Also, please make sure that in your Django settings in REST_FRAMEWORK DEFAULT_AUTHENTICATION_CLASSES contains JWT authentication:

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