如何限制来自GraphQL API端点的匿名用户? [英] How to restrict anonymous users from GraphQL API endpoint?

查看:131
本文介绍了如何限制来自GraphQL API端点的匿名用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django有两种方法.

Django has two approaches.

  1. 常规DRF将用户限制在中间件级别.因此,未登录的用户无法访问任何内容.

  1. Regular DRF restricts user on Middleware level. So not logged in user doesn't reach anything.

GraphQL使用每个方法"方法.因此,中间件传递所有请求和每种方法.但是之后方法会调用装饰器.

GraphQL, on contrary, uses "per method" approach. So middleware passes all the request and each method. But afterward method calls decorator.

除了GraphQL,我想实现第一种方法.但是在那种情况下,我需要打开登录突变的路径.如何从有效载荷中提取突变名称?

I want to implement 1st approach but for GraphQL. But in that case I need to open path for login mutation. How can I extract mutation name from payload?

推荐答案

如果要将GraphQL API端点限制为Django登录用户,则可以通过使用LoginRequiredMixin

If you want restrict a GraphQL API endpoint to Django logged in users, you can do it by extending GraphQLView with LoginRequiredMixin

from django.contrib.auth.mixins import LoginRequiredMixin
from graphene_django.views import GraphQLView

class PrivateGraphQLView(LoginRequiredMixin, GraphQLView):
    """Adds a login requirement to graphQL API access via main endpoint."""
    pass

,然后将此视图添加到您的urls.py中,例如

and then adding this view to your urls.py like

path('api/', PrivateGraphQLView.as_view(schema=schema), name='api')

按照文档.

如果您不想保护整个API,则可以为未受保护的查询和变异创建另一个架构和终结点,从而可以将两者明确分隔.例如在urls.py中:

If you don't want to protect your entire API, you can create another schema and endpoint for the unprotected queries and mutations, which allows a clear separation between each. For example in urls.py:

path('public_api/', GraphQLView.as_view(schema=public_schema), name='public_api')

请注意,每个API终结点必须至少具有一个查询才能工作,否则将导致断言错误.

Note that every API endpoint must have at least one query to work or it will cause an assertion error.

这篇关于如何限制来自GraphQL API端点的匿名用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆