Li Qi
Li Qi

Reputation: 43

Django Rest API with okta OAUTH token authentication

I have a problem with Okta token authentication, I know how to authenticate with drf token and jwt token auth.

In my project, I have to use okta token which is a type of jwt as well, however, this token is generated by front-end and send back to me in the request

so here you can see how I authenticate the okta token with okta_jwt package:

def post(self, request, *args, **kwargs):

    access_token = request.META.get('HTTP_AUTHORIZATION')
    try:
        validate_token(access_token, config.issuer, config.aud, config.client_id)
    except Exception as e:
        return JsonResponse({"result": e.args[0]}, status=400)

    ..........

Basically I have to take the token out from the header and check with okta_jwt to see if it's legal

Obviously, I don't think it's a good solution and it's hard to do unit test

Can anyone provide a better solution for this?

Thanks

Upvotes: 3

Views: 2087

Answers (1)

Qi Li
Qi Li

Reputation: 56

I found the solution:

I just created the custom authentication inherit from BaseAuthentication. In the Custom authentication, you can do whatever authenticating process you want:

class OktaAuthentication(authentication.BaseAuthentication):

   def authenticate(self, request):
      access_token = request.META.get('HTTP_AUTHORIZATION')
      if not access_token:
        return None

    payload = validate_token(access_token, config.issuer, config.aud, config.client_id)

    try:
        user = get_user_model().objects.get(email=payload['sub'])

    except User.DoesNotExist:
        raise exceptions.AuthenticationFailed('No such user')

    return user, None

In the setting.py, making sure you have the custom authentication added as the Default:

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'core.authentication.OktaAuthentication',
)}

In the views:

authentication_classes = (OktaAuthentication,)
permission_classes = (IsAuthenticated,)

Upvotes: 2

Related Questions