首页 > 解决方案 > GraphQl 未授权使用 JWT 令牌

问题描述

我正在关注这个博客教程......到目前为止一切都很好,我正在生成然后令牌......使用 GraphQl 的默认模板

input->

   mutation{
    tokenAuth(username:"riyad", password:"1234"){
    token
     }
  }
 
output-> 

   {
  "data": {
    "tokenAuth": {
      "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InJpeWFkIiwiZXhwIjoxNTkzNTI0Nzk5LCJvcmlnX2lhdCI6MTU5MzUyNDQ5OX0.DjploWeEwLpRBZX0wz5_NSqz22qDHbgNI26uXs6fuXE"
              }
          }
      }

但是当我使用 insominia 获取时,我没有得到用户授权....而是引发了我创建的异常... 发布请求

添加了标头令牌

我的架构文件->

class UserType(DjangoObjectType):
    class Meta:
        model = get_user_model()


class Query(graphene.ObjectType):
    me = graphene.Field(UserType)
    users = graphene.List(UserType)

    def resolve_users(self, info, **kwargs):
        return get_user_model().objects.all()

    def resolve_me(self, info):
        user = info.context.user
        if user.is_anonymous:
            raise Exception('Not logged in!')

        return user

我额外添加的 settings.file

GRAPHENE = {
    'SCHEMA': 'hackernews.schema.schema'
}

'''python(path=“…/graphql-python/hackernews/hackernews/settings.py”) GRAPHENE = { ‘SCHEMA’: ‘mysite.myschema.schema’, ‘MIDDLEWARE’: [ ‘graphql_jwt.middleware.JSONWebTokenMiddleware’, ], } '''

AUTHENTICATION_BACKENDS = [
    'graphql_jwt.backends.JSONWebTokenBackend',
    'django.contrib.auth.backends.ModelBackend',
]

我的主应用程序->

import graphene
import links.schema
import users.schema
import graphql_jwt


class Query(users.schema.Query, links.schema.Query, graphene.ObjectType):
    pass


class Mutation(users.schema.Mutation, links.schema.Mutation, graphene.ObjectType):
    token_auth = graphql_jwt.ObtainJSONWebToken.Field()
    verify_token = graphql_jwt.Verify.Field()
    refresh_token = graphql_jwt.Refresh.Field()


schema = graphene.Schema(query=Query, mutation=Mutation)

标签: djangographqlgraphene-django

解决方案


我通过移动解决了它

'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware', ], 

它位于 settings.py 文件中的 GRAPHENE 变量到同一文件中的 MIDDLEWARE 变量中。

参考 --> https://github.com/howtographql/howtographql/issues/983


推荐阅读