首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在django-graphql-jwt中使用@login_required进行查询/突变会导致graphql.error.located_error.GraphQLLocatedError

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

Stack Overflow用户
提问于 2021-02-26 01:21:15
回答 1查看 572关注 0票数 3

我是GraphQL的乞讨者,开始使用Django开发一个小应用程序,并决定使用django-graphql-jwt进行身份验证。

我可以使用getTokenAuth、VerifyToken和RefreshToken,没有任何问题。但是,当我尝试使用带有装饰器@login_required的查询时,我得到的只是一个"GraphQLLocatedError: You‘t to’t permission to perform action“响应。但是,不知何故,单元测试运行得很好。

我的代码:

settings.py

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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"])

请求信息

代码语言:javascript
复制
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}}
EN

回答 1

Stack Overflow用户

发布于 2021-03-08 18:37:46

我认为您应该按如下方式更改您的queries.py代码片段:

代码语言:javascript
复制
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

请注意,最新的graphene版本(v0.3.0)有一个未解决的问题,您必须将PyJWT==1.7.0包添加到requirements.txt中才能解决该问题-( relevant question)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66373395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档