【问题标题】:How to use Graphene GraphQL framework with Django REST Framework authentication如何将 Graphene GraphQL 框架与 Django REST 框架身份验证一起使用
【发布时间】:2016-12-25 21:27:26
【问题描述】:

我在 Django 中有一些 REST API 端点,我想将 the same authentication 用于 Graphene。 documentation 不提供任何指导。

【问题讨论】:

    标签: python django rest authentication graphql


    【解决方案1】:

    例如,如果您在 API 视图中使用 authentication_classes = (TokenAuthentication,),则可以将端点添加到以这种方式装饰的 GraphQLView:

    urls.py:

    # ...
    from rest_framework.authentication import TokenAuthentication
    from rest_framework.permissions import IsAuthenticated
    from rest_framework.decorators import authentication_classes, permission_classes, api_view
    
    def graphql_token_view():
        view = GraphQLView.as_view(schema=schema)
        view = permission_classes((IsAuthenticated,))(view)
        view = authentication_classes((TokenAuthentication,))(view)
        view = api_view(['GET', 'POST'])(view)
        return view
    
    urlpatterns = [
    # ...
        url(r'^graphql_token', graphql_token_view()),
        url(r'^graphql', csrf_exempt(GraphQLView.as_view(schema=schema))),
        url(r'^graphiql', include('django_graphiql.urls')),
    # ...
    

    请注意,我们添加了一个新的 ^graphql_token 端点并保留了 GraphiQL 工具使用的原始 ^graphql

    然后,您应该在 GraphQL 客户端中设置 Authorization 标头并指向 graphql_token 端点。


    更新:请参阅this GitHub issue,人们在其中提出了替代解决方案和完整的工作示例。

    【讨论】:

    • 这仍然对您有用吗?我正在尝试对 SessionAuthentication 做同样的事情,但是当它尝试读取请求的正文时,我从 graphene-django 收到错误消息?
    • 仍然有效,但我没有最新版本的软件包。我使用的答案是:Django==1.8.3 djangorestframework==3.2.2 django-graphiql==0.4.4 graphene==0.10.2 graphql-core==0.5.3 graphql-django-view==1.3 graphql-relay= =0.4.4
    • 可以发post请求吗?
    • @KentDelaCruzFueconcillo 是的。
    【解决方案2】:

    添加一些我在遵循此集成时必须采取的额外步骤:

    class RTGraphQLView(GraphQLView):
    
    def parse_body(self, request):
        if type(request) is rest_framework.request.Request:
            return request.data
        return super().parse_body(request)
    

    Graphene 期待 .body attr,但 DRF 会读取它并将其附加到 .data,然后再传递给 GraphQLView。

    【讨论】:

      猜你喜欢
      • 2013-06-29
      • 2017-09-26
      • 2017-11-02
      • 2023-04-07
      • 2019-03-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      相关资源
      最近更新 更多