簡體   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

我是 GraphQL 的初學者,並開始使用 Django 開發一個小型應用程序,並決定使用 django-graphql-jwt 進行身份驗證。

我可以毫無問題地使用 getTokenAuth、VerifyToken 和 RefreshToken。 但是當我嘗試使用帶有裝飾器@login_required 的查詢時,我得到的只是“GraphQLLocatedError:您無權執行此操作”響應。 但是,不知何故,單元測試運行良好。

我的代碼:

設置.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",
]

查詢.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}!"

測試.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"])

請求信息

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}}

我認為您應該更改您的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

請注意,最新的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