eadwinCode / django-ninja-jwt

A JSON Web Token authentication plugin for the Django REST Framework.
https://eadwincode.github.io/django-ninja-jwt/
MIT License
154 stars 21 forks source link

How can I use this to verify Auth0 token? #32

Open magedhelmy1 opened 1 year ago

magedhelmy1 commented 1 year ago

Below is a working example from Django Rest Framework:


REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ],
    'EXCEPTION_HANDLER': 'messages_api.views.api_exception_handler',
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication',
    ],
}

# JWT

AUTH0_DOMAIN = get_env_var('AUTH0_DOMAIN')
AUTH0_AUDIENCE = get_env_var('AUTH0_AUDIENCE')

SIMPLE_JWT = {
    'ALGORITHM': 'RS256',
    'JWK_URL': f'https://{AUTH0_DOMAIN}/.well-known/jwks.json',
    'AUDIENCE': AUTH0_AUDIENCE,
    'ISSUER': f'https://{AUTH0_DOMAIN}/',
    'USER_ID_CLAIM': 'sub',
    'AUTH_TOKEN_CLASSES': ('authz.tokens.Auth0Token',),
}

class ProtectedMessageApiView(MessageApiView):
    text = "This is a protected message."
    permission_classes = [IsAuthenticated]

Now, how to make it check that the Auth0 is correct and protect the below view until the Auth0 is verified:

@router.get("/protected", response={200: MessageSchema, 403: ErrorResponse})
def protected_message(request):
    if not request.auth:
        return ErrorResponse(message="User is not authenticated"), 403
    return get_message("This is a protected message.")
eadwinCode commented 1 year ago

@magedhelmy1 I dont quite get your question. Can you explain more please?

eadwinCode commented 1 year ago
from ninja_jwt.authentication import JWTAuth
...

@router.get("/protected", response={200: MessageSchema, 403: ErrorResponse}, auth=JWTAuth())
def protected_message(request):
    if not request.auth:
        return ErrorResponse(message="User is not authenticated"), 403
    return get_message("This is a protected message.")