如何将 Graphene GraphQL 框架与 Django REST Framework 身份验证一起使用
How to use Graphene GraphQL framework with Django REST Framework authentication
我在 Django 中得到了一些 REST API 端点,我想使用 the same authentication for Graphene. The documentation 没有提供任何指导。
例如,如果您在 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
header 并指向 graphql_token
端点。
更新:请参阅 this GitHub issue 人们建议的替代解决方案和完整的工作示例。
添加一些我在进行此集成时必须采取的额外步骤:
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
属性,但 DRF 读取它并将其附加到 .data
,然后再传递给 GraphQLView。
我在 Django 中得到了一些 REST API 端点,我想使用 the same authentication for Graphene. The documentation 没有提供任何指导。
例如,如果您在 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
header 并指向 graphql_token
端点。
更新:请参阅 this GitHub issue 人们建议的替代解决方案和完整的工作示例。
添加一些我在进行此集成时必须采取的额外步骤:
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
属性,但 DRF 读取它并将其附加到 .data
,然后再传递给 GraphQLView。