Search code examples
djangoauthenticationdjango-rest-frameworkhttp-headersdjango-rest-framework-jwt

Getting django rest framework jwt authentication to work [django rest, angular 5]


so I have installed djanogo rest framework JWT and set the settings and authetication classes. According to this guide. I will leave out the settings as they are correct, and that is not where the problem lies. It is also to not post too much code

https://jpadilla.github.io/django-rest-framework-jwt/

I then make a call to a authorization view on my server from the front end

 let token = "hardcoded token just to get the service working"; 
    if(token != null){
      this.authservice.authorizetoken(token)
        .subscribe(
          (req: any)=>{
            console.log(req);
          }
        );

// grab the permissions a user has and who they are by token
    authorizetoken(token){
      return this.http.get(userauthorization, {
        headers: new HttpHeaders().set('Authorization', 'JWT' + token )
      });
    }

then in my django here is the view code:

class UserAuthorization(APIView):
    authentication_classes = (JSONWebTokenAuthentication,)
    def get(self, request, *args, **kwargs):
        print(request.user)
        return Response({})

but I keep getting anonymousUser returned. Shouldn't it be a user object since I am passing a token in the header?

I dont know what I am doing wrong.


Solution

  • According to documentation the headers should be in format Authorization: JWT <your_token>. When you are setting the token in headers inside your authorizetoken function, you are missing a white-space between 'JWT'+ token. This might be the problem for not authenticating the user. Have you tried the endpoint with Postman?