问题描述
我在 Django 中有一些 REST API 端点,我想使用 对石墨烯进行相同的认证.文档不提供任何指导.
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.
推荐答案
例如,如果您在 API 视图中使用 authentication_classes = (TokenAuthentication,)
,则可以向 GraphQLView 添加端点以这种方式装饰:
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')),
# ...
请注意,我们添加了一个新的 ^graphql_token
端点并保留了 GraphiQL 工具使用的原始 ^graphql
.
Note that we added a new ^graphql_token
endpoint and kept the original ^graphql
which is used by the GraphiQL tool.
然后,您应该在 GraphQL 客户端中设置 Authorization
标头并指向 graphql_token
端点.
Then, you should set the Authorization
header in your GraphQL client and point to the graphql_token
endpoint.
更新:请参阅此 GitHub 问题,其中人们提出了替代解决方案和完整的工作示例.
UPDATE: See this GitHub issue where people have suggested alternative solutions and full working examples.
这篇关于如何在 Django REST Framework 身份验证中使用 Graphene GraphQL 框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!