djangodjango-rest-frameworkdjoserdjango-ninja

Django ninja token authentication with djoser


I have implemented CRUD with Django Ninja framework, but now I want auth in my app, I had installed and config Djoser, so now I can generate tokens, but I don't know how to verify in my CRUD's

class AuthBearer(HttpBearer):
    def authenticate(self, request, token):
        if token == "supersecret":
            return token

@api.get("/bearer", auth=AuthBearer())
def bearer(request):
    return {"token": request.auth}

I shoud able to check token inside "AuthBearer" function, but I don't know how

my repo (link)


Solution

  • so basically you have to extend Ninja's HttpBearer class and implement authenticate method, which will accept request and token as parameters. This method returns None if the user is not authenticated, and a string which will be populated in request.auth if the user is authenticated. Usually this string will be the username so you can use it in all your endpoints. Something like this (I am using PyJWT for token decoding):

    import jwt
    from ninja.security import HttpBearer
    
    class AuthBearer(HttpBearer):
        def authenticate(self, request, token):
            try:
                #JWT secret key is set up in settings.py
                JWT_SIGNING_KEY = getattr(settings, "JWT_SIGNING_KEY", None)
                payload = jwt.decode(token, JWT_SIGNING_KEY, algorithms=["HS256"])
                username: str = payload.get("sub")
                if username is None:
                    return None
            except jwt.PyJWTError as e:
                return None
    
            return username