1

I have written a very basic custom authentication class in order to implement the simple JWT library for my custom authentication needs.

I generate tokens manually and then send the access token to my API. By default, this would be enough but since I do not use the default Django user Model, I get "User not found". This is because I need to implement a custom authentication backend.

I need to read that token in order to query the database with the given user id and check if that token is valid as well. In my example, I have fixed number 2.

enter image description here

class ExampleAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        try:
            user = vAuthUser.objects.get(pk=2) #this should receive the user_id from the token
        except:
            raise AuthenticationFailed('No such user')

        return (user, None)

My API looks like:

class MyAPI(APIView):
    authentication_classes = (ExampleAuthentication,)
    permission_classes = (IsAuthenticated ,)

   def get()...
2
  • so exactly what is your question? it's unclear what you need Commented Dec 27, 2020 at 13:10
  • Use simple JWT with custom authentication doesn't work as it should. I generate the token send it but how can I read it in the custom authentication class in order to authenticate user correctly? Commented Dec 27, 2020 at 13:32

1 Answer 1

3

Try this:

from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.models import User
user = User.objects.first()
refresh = RefreshToken.for_user(user)
raw_token = str(refresh.access_token)

jwt_a = JWTAuthentication()
validated_token = jwt_a.get_validated_token(raw_token)
repr(validated_token)
print(validated_token["user_id"])

Here I feed a raw access token to get_validated_token() method of JWTAuthentication class. it returns a dictionary with these keys: token_type, jti, user_id, exp, and their associated values.
I've used the default Django User Model for my sample, but it should work with your custom Model.
There are more useful methods like get_header(). check this document and this one too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.