How to use Graphene GraphQL framework with Django REST Framework authentication

后端 未结 2 1735
心在旅途
心在旅途 2020-12-24 02:55

I got some REST API endpoints in Django and I\'d like to use the same authentication for Graphene. The documentation does not provide any guidance.

2条回答
  •  太阳男子
    2020-12-24 03:16

    For example, if you are using authentication_classes = (TokenAuthentication,) in your API views, you could add an endpoint to a GraphQLView decorated in this way:

    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')),
    # ...
    

    Note that we added a new ^graphql_token endpoint and kept the original ^graphql which is used by the GraphiQL tool.

    Then, you should set the Authorization header in your GraphQL client and point to the graphql_token endpoint.


    UPDATE: See this GitHub issue where people have suggested alternative solutions and full working examples.

提交回复
热议问题