简体   繁体   English

使用 Django GraphQL JWT 和 Graphene Relay 进行身份验证和授权

[英]Authentication and Authorization with Django GraphQL JWT and Graphene Relay

I would like to ask how I can do authentication and query tags limited to a specific user (owner) using Graphen Relay and Django JWT.我想问一下如何使用 Graphen Relay 和 Django JWT 对特定用户(所有者)进行身份验证和查询标签。 Here is my Model:这是我的模型:

class Tag(models.Model):
"""Tag to be used for a objective"""
name = models.CharField(max_length=255)
user = models.ForeignKey(
    settings.AUTH_USER_MODEL,
    related_name='tag',
    on_delete=models.CASCADE,
)

Here is my Schema code:这是我的架构代码:

class TagNode(DjangoObjectType):
class Meta:
    model = Tag
    filter_fields = ['name']
    interfaces = (relay.Node,)

Here is my Query:这是我的查询:

class Query(graphene.ObjectType):
    tag = relay.Node.Field(TagNode)
    all_tags = DjangoFilterConnectionField(TagNode)

    def resolve_all_tags(self, info):

        # context will reference to the Django request
        print(info.context.user)
        if not info.context.user.is_authenticated:
            return Tag.objects.none()
        else:
            return Tag.objects.filter(user=info.context.user)

Here is the document for Django JWT: https://github.com/flavors/django-graphql-jwt but I do not know how to get the user (already use info.context.user) but it does not work, when I tried to add Authorization (JWT token) in the header or as an argument.这是 Django JWT 的文档: https : //github.com/flavors/django-graphql-jwt但我不知道如何获取用户(已经使用 info.context.user)但它不起作用,当我尝试在标头中或作为参数添加授权(JWT 令牌)。 It also does not work.它也不起作用。

Basically you are doing everything correctly and your user should be fetched successfully.基本上你做的一切都是正确的,你的用户应该被成功获取。 I've just checked and it works in my case, I use JWT like a cookie but it doesn't matter.我刚刚检查过,它适用于我的情况,我像使用 cookie 一样使用 JWT,但没关系。

Had you authorized your user when tried to get tags?您在尝试获取标签时是否已授权您的用户?
Because regarding JWT you need to authorize your user and receive the JWT token.因为关于 JWT,您需要授权您的用户并接收 JWT 令牌。 Only after that the real user will be presented in the request when you call the tags query.只有在此之后,当您调用标签查询时,真实用户才会出现在请求中。 Otherwise the user will be anonymous.否则用户将是匿名的。

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

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