Graphene-Django 不向 React-Apollo 发送 HTTPOnly JWT Cookie

问题描述

嗨,我一直在为 Django 服务器使用 GrapheneGraphQL 制作应用程序,React 客户端将使用 Apollo 访问该服务器.我正在使用 graphql_jwt 进行身份验证。

我已经设置了我的 GraphQL 服务器和客户端代码来读取 JWT,但我了解到 localStorage 不够安全,cookie 也不够安全。我设法在发出 tokenAuth 请求时找到了一种设置 HTTPOnly cookie 的方法,并且 cookie 仍然存在并且在 GraphiQL (localhost:8000) 中正常工作。

JWT HHTPOnly Cookies Set

我使用 jwt_cookiegraphql_jwt.decorators 装饰器成功做到了这一点

from django.contrib import admin
from django.urls import path
from graphene_django.views import GraphQLView
from django.views.decorators.csrf import csrf_exempt
from graphql_jwt.decorators import jwt_cookie

urlpatterns = [
    path('admin/',admin.site.urls),path('graphql/',jwt_cookie(csrf_exempt(GraphQLView.as_view(graphiql=True))))
]

不幸的是,当我从 Apollo (localhost:3000) 调用 tokenAuth 端点时,它既没有设置 cookie,也不能从我的后件中访问它(现在我想到它是有道理的)。 same-origininclude 凭据均不适用于服务器 HttpLinkApolloClient 本身。

import { 
  ApolloClient,gql,ApolloProvider,HttpLink,from,useQuery,ApolloLink
} from '@apollo/client';
import { onError } from '@apollo/client/link/error';
import { setContext } from 'apollo-link-context';

const errorLink = onError(({ graphQLErrors,networkError }) => {
  if (graphQLErrors) {
    graphQLErrors.forEach(({ message }) => {
      console.log(message);
    });
  }
  if (networkError) {
    console.log(networkError.message)
  }
});
const afterwareLink = new ApolloLink((operation,forward) => {
  return forward(operation).map(response => {
    const context = operation.getContext();
    const { response: { headers } } = context;
    console.log(headers);
    return response;
  });
});


const link = from([
  errorLink,setContext((operation) => {
    console.log("HITTING SET CONTEXT");
    // const token = localStorage.getItem('authToken');
    const token = Cookies.get('authToken');
    console.log(token);
    return {
      headers: {
        Authorization: token ? `JWT ${token}` : ''
      }
    }
  }),afterwareLink,new HttpLink({ uri: 'http://localhost:8000/graphql/' })
]);

const client = new ApolloClient({
  link,cache,typeDefs,credentials: 'include'
});

请忽略 refreshTokenauthToken 值。我使用 js-cookie 包设置它们。但是正如您所看到的,Headers 是空的,并且不是在客户端登录时设置的,而是在服务器上设置的。

enter image description here

问题:

如何将 jwt 响应头传递给前端?

解决方法

所以我能够解决这个问题。我在 Github 上发布了我的决议

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