JWT Authentication: Use UI Token to Authenticate Graphene / Django Requests (GraphQL)?

I am working on a project with the following architecture:

  • UI: respond to client and server rendering on Node server, Apollo Client for GraphQL,

  • API: Django processes GraphQL queries through Graphene.

I am using Auth0 (based on JWT) for my interface authentication. I would like to use a token that I can execute to authenticate my user in the context of the GraphQL query request APIs.

[Edit2]

To pass the token to my API, I use:

const idToken = cookie.load('idToken') || null;
networkInterface.use([{
  applyMiddleware(req, next) {
    if (!req.options.headers) {
      req.options.headers = {};  // Create the header object if needed.
    }
    req.options.headers.authorization = `Bearer ${idToken}`;
    next();
  }
}]);

Then I need to get it in Django: I use django-jwt-auth and the code suggested by @Craig Ambrose.

( ), : " ".

, , jwt.io.

Django?

+4
2

, django-jwt-auth ( Auth0)

JSONWebTokenAuthMixin, GraphQLView graphene_django, .

from jwt_auth.mixins import JSONWebTokenAuthMixin

class AuthGraphQLView(JSONWebTokenAuthMixin, GraphQLView):
    pass

urlpatterns = [
    url(r'^graphql', csrf_exempt(AuthGraphQLView.as_view(schema=schema))),
    url(r'^graphiql', include('django_graphiql.urls')),
]

, , graphiql , . auth cookie , dev, .

from jwt_auth.mixins import JSONWebTokenAuthMixin

class OptionalJWTMixin(JSONWebTokenAuthMixin):
    def dispatch(self, request, *args, **kwargs):
        auth = get_authorization_header(request)
        if auth:
            return super(OptionalJWTMixin, self).dispatch(request, *args, **kwargs)
        else:
            return super(JSONWebTokenAuthMixin, self).dispatch(request, *args, **kwargs)


class AuthGraphQLView(OptionalJWTMixin, GraphQLView):
    pass

urlpatterns = [
    url(r'^graphql', csrf_exempt(AuthGraphQLView.as_view(schema=schema))),
    url(r'^graphiql', include('django_graphiql.urls')),
]
+5

:

@Craig Ambrose django-jwt-auth. Github, , Auth0.

def jwt_get_user_id_from_payload_handler(payload):
    sub = payload.get('sub')
    Auth0User = import_string('project.models.Auth0User')
    auth0_user = Auth0User.objects.filter(auth0_id=sub)[0]
    user_id = auth0_user.user.id
    return user_id

JWT_PAYLOAD_GET_USER_ID_HANDLER = jwt_get_user_id_from_payload_handler
auth0_key = '<MyAuth0SECRET>'
JWT_SECRET_KEY = base64.b64decode(auth0_key.replace("_","/").replace("-","+"))
JWT_VERIFY = True
JWT_AUTH_HEADER_PREFIX = 'Bearer'
JWT_AUDIENCE = '<MyAuth0CLIENT_ID>'

Aut0User OnoToOne Django auth0_id.

0

Source: https://habr.com/ru/post/1650851/


All Articles