如何使用Graphene GraphQL框架与Django REST Framework身份验证

Ric*_*ven 20 python authentication django rest graphql

我在Django中获得了一些REST API端点,我想对Graphene 使用相同的身份验证.该文件没有提供任何指引.

Ric*_*ven 21

例如,如果您authentication_classes = (TokenAuthentication,)在API视图中使用,则应将端点添加到以这种方式修饰的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')),
# ...
Run Code Online (Sandbox Code Playgroud)

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

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