问题描述
我在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框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!