【问题标题】:Graphene-Django not Sending HTTPOnly JWT Cookie to React-ApolloGraphene-Django 不向 React-Apollo 发送 HTTPOnly JWT Cookie
【发布时间】:2021-08-22 18:14:59
【问题描述】:

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

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

我设法用来自graphql_jwt.decoratorsjwt_cookie 装饰器做到了这一点

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 包设置它们。但正如您所见,标头是空的,并没有在客户端登录时设置,而是在服务器上。

问题:

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

【问题讨论】:

    标签: cookies graphql jwt apollo httponly


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-04-16
      • 2020-11-19
      • 2021-02-07
      • 2018-07-20
      • 2021-08-26
      • 2021-08-05
      • 2017-06-20
      • 2020-03-12
      相关资源
      最近更新 更多