在Django中,如何保护Graphene GraphQL端点以供API使用?

2024-04-28 10:22:40 发布

您现在位置:Python中文网/ 问答频道 /正文

Graphene提供了到Django的GraphQL集成,并提供了创建URL端点的视图。问题是如何保护端点以供API使用?{a1}是使用LoginRequiredMixin,这对于登录用户来说非常好,但不能用作API

我曾尝试将其与DRF令牌集成,但最终还是使用了需要CSRF的会话中间件。唯一有效的解决方案是添加一个CSRF豁免修饰符,但我担心这会打开一个安全漏洞

# urls.py
path("graphiql/", root_views.SessionGraphQLView.as_view(graphiql=True), name="graphiql"),
path("graphql/", root_views.TokenGraphQLView.as_view(graphiql=False), name="graphql"),


# views.py
class TokenLoginRequiredMixin(AccessMixin):

    """A login required mixin that allows token authentication."""

    def dispatch(self, request, *args, **kwargs):
        """If token was provided, ignore authenticated status."""
        http_auth = request.META.get("HTTP_AUTHORIZATION")

        if http_auth and "Token" in http_auth:
            pass

        elif not request.user.is_authenticated:
            return self.handle_no_permission()

        return super().dispatch(request, *args, **kwargs)


@method_decorator(csrf_exempt, name="dispatch")
class TokenGraphQLView(TokenLoginRequiredMixin, GraphQLView):
    authentication_classes = [TokenAuthentication]


class SessionGraphQLView(LoginRequiredMixin, GraphQLView):
    pass

Tags: pathnamepyauthapihttprequestroot