eadwinCode/django-ninja-jwt

How can I use this to verify Auth0 token?

magedhelmy1 opened this issue · 2 comments

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.")

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

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.")