简体   繁体   English

在 django-graphql-jwt 中使用 @login_required 进行查询/突变会导致 graphql.error.located_error.GraphQLLocatedError

[英]Using @login_required for queries/mutations in django-graphql-jwt leads to graphql.error.located_error.GraphQLLocatedError

I'm a begginer with GraphQL and started developing a small app using Django and decided to use django-graphql-jwt for authentication.我是 GraphQL 的初学者,并开始使用 Django 开发一个小型应用程序,并决定使用 django-graphql-jwt 进行身份验证。

I can use the getTokenAuth, VerifyToken and RefreshToken with no problem.我可以毫无问题地使用 getTokenAuth、VerifyToken 和 RefreshToken。 But when I try to use a query with decorator @login_required, all I get is a "GraphQLLocatedError: You do not have permission to perform this action" response.但是当我尝试使用带有装饰器@login_required 的查询时,我得到的只是“GraphQLLocatedError:您无权执行此操作”响应。 But, somehow, the unit tests are working nicely.但是,不知何故,单元测试运行良好。

My code:我的代码:

settings.py设置.py

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

GRAPHENE = {
    "SCHEMA": "myproject.graphql.api.schema",
    "MIDDLWARE": [
        "graphql_jwt.middleware.JSONWebTokenMiddleware",
    ],
}

GRAPHQL_JWT = {
    "JWT_ALLOW_ARGUMENT": True,
    "JWT_VERIFY_EXPIRATION": True,
    "JWT_EXPIRATION_DELTA": timedelta(minutes=5),
    "JWT_REFRESH_EXPIRATION_DELTA": timedelta(days=7),
    "JWT_AUTH_HEADER_NAME": "Authorization",
    "JWT_AUTH_HEADER_PREFIX": "Bearer",
}

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

queries.py查询.py

from graphene import String, ObjectType
from graphql_jwt.decorators import login_required

class HelloQuery(ObjectType):
    hello = String(name=String(default_value="stranger"))

    @login_required
    def resolve_hello(self, info, name):
        return f"Hello {name}!"

tests.py测试.py

from graphql_jwt.testcases import JSONWebTokenTestCase
from users.factories import UserFactory

class QueryTest(JSONWebTokenTestCase):
    def setUp(self):
        self.user = UserFactory()
        self.client.authenticate(self.user)
        super().setUp()

    def test_00_hello(self):
        """
        This test evaluates the HelloQuery
        """

        query = """
            query hello {
                hola: hello(name: "tester")
            }
        """
        result = self.client.execute(query)
        self.assertIsNone(result.errors)
        self.assertEqual("Hello tester!", result.data["hola"])

Request info请求信息

POST http://localhost:8000/graphql
200
34 ms
Network
Request Headers
X-CSRFToken: 7ZZrDHmpkly1FHexdLASComfiqCo81iaHOHJuywRabRHsdIDgKbBXK3ex687G7Xt
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImpvY2hvIiwiZXhwIjoxNjE0MjczNTcxLCJvcmlnSWF0IjoxNjE0MjczMjY0fQ.C6yDzim5jliu6yIMDJ70Xl3WPP69HpYTR0VSGmy0brc
Content-Type: application/json
User-Agent: PostmanRuntime/7.26.10
Accept: */*
Cache-Control: no-cache
Postman-Token: 80a0c7fe-34c1-4972-8c3f-9342e9d047e1
Host: localhost:8000
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 63
Cookie: JWT=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImpvY2hvIiwiZXhwIjoxNjE0MjczNTcxLCJvcmlnSWF0IjoxNjE0MjczMjY0fQ.C6yDzim5jliu6yIMDJ70Xl3WPP69HpYTR0VSGmy0brc; csrftoken=7ZZrDHmpkly1FHexdLASComfiqCo81iaHOHJuywRabRHsdIDgKbBXK3ex687G7Xt
Request Body
query: "query hello {
    hola: hello(name: "tester")
}"
variables: ""
Response Headers
Date: Thu, 25 Feb 2021 17:14:37 GMT
Server: WSGIServer/0.2 CPython/3.9.1
Content-Type: application/json
Vary: Cookie
X-Frame-Options: DENY
Content-Length: 149
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Set-Cookie: csrftoken=7ZZrDHmpkly1FHexdLASComfiqCo81iaHOHJuywRabRHsdIDgKbBXK3ex687G7Xt; expires=Thu, 24 Feb 2022 17:14:37 GMT; Max-Age=31449600; Path=/; SameSite=Lax
Response Body
{"errors":[{"message":"You do not have permission to perform this action","locations":[{"line":2,"column":5}],"path":["hola"]}],"data":{"hola":null}}

I think you should change your queries.py code snippet as follows:我认为您应该更改您的queries.py代码片段,如下所示:

from graphene import String, ObjectType

class HelloQuery(ObjectType):
    hello = String(name=String(default_value="stranger"))

    def resolve_hello(self, info, name):
        user = info.context.user
        if user.is_authenticated:
            return f"Hello {name}!"
        return None

Note that the latest graphene version ( v0.3.0 ) has an unresolved problem in which you have to add PyJWT==1.7.0 package into your requirements.txt to resolve that – (The relevant question )请注意,最新的graphene版本 ( v0.3.0 ) 有一个未解决的问题,您必须将PyJWT==1.7.0 package 添加到您的requirements.txt中以解决该问题 – (相关问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM