How to restrict anonymous users from GraphQL API endpoint?

北城以北 提交于 2020-01-21 20:10:29

问题


Django has two approaches.

  1. Regular DRF restricts user on Middleware level. So not logged in user doesn't reach anything.

  2. GraphQL, on contrary, uses "per method" approach. So middleware passes all the request and each method. But afterward method calls decorator.

I want to implement 1st approach but for GraphQL. But in that case I need to open path for login mutation. How can I extract mutation name from payload?


回答1:


If you want restrict a GraphQL API endpoint to Django logged in users, you can do it by extending GraphQLView with LoginRequiredMixin

from django.contrib.auth.mixins import LoginRequiredMixin
from graphene_django.views import GraphQLView

class PrivateGraphQLView(LoginRequiredMixin, GraphQLView):
    """Adds a login requirement to graphQL API access via main endpoint."""
    pass

and then adding this view to your urls.py like

path('api/', PrivateGraphQLView.as_view(schema=schema), name='api')

in the usual way as per the docs.

If you don't want to protect your entire API, you can create another schema and endpoint for the unprotected queries and mutations, which allows a clear separation between each. For example in urls.py:

path('public_api/', GraphQLView.as_view(schema=public_schema), name='public_api')

Note that every API endpoint must have at least one query to work or it will cause an assertion error.




回答2:


Not sure if it serves your purpose, but I've used the following library which used JWT authentication with graphene similar to how JWT with DRF works!

https://github.com/flavors/django-graphql-jwt



来源:https://stackoverflow.com/questions/51116456/how-to-restrict-anonymous-users-from-graphql-api-endpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!