JWT身份验证:使用UI令牌验证Graphene/Django(GraphQL)查询?

vwr*_*bel 4 authentication django node.js jwt auth0

我正在开发一个具有以下架构的项目:

  • UI:通过Node服务器,Apollo Client for GraphQL对客户端和服务器端呈现进行反应,

  • API:Django通过Graphene处理GraphQL查询.

我使用Auth0(基于JWT)进行前端身份验证.我想在GraphQL查询API端的上下文中使用我获得的令牌来验证我的用户.

[EDIT2]

要将令牌传递给我的API,我使用:

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();
  }
}]);
Run Code Online (Sandbox Code Playgroud)

然后我需要在Django中检索它:我使用django-jwt-auth和@Craig Ambrose提出的代码.

我的授权标题被接收并解码(我可以获得有效负载)但是在验证签名时出现问题:我得到"解码签名错误".

这很奇怪,因为我在jwt.io上测试时验证了签名.

如何在Django端进行身份验证?

小智 5

我刚刚使用django-jwt-auth(不使用Auth0)完成了这个

该软件包提供了一个JSONWebTokenAuthMixin,您可以将其与graphene_django中的GraphQLView结合使用.

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')),
]
Run Code Online (Sandbox Code Playgroud)

这有效,但我发现graphiql停止工作,因为它没有发送到令牌.我想继续使用基于cookie的auth,为了开发目的,所以将其更改为以下内容.

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')),
]
Run Code Online (Sandbox Code Playgroud)