首页 > 解决方案 > 如何使用 Apollo 从 GraphQL Mutation 设置 Auth token cookie

问题描述

我正在使用来自 graphql-yoga 的 GraphQLServer 来处理请求。此时我的后端能够与我的 React 前端通信,我可以进行 graphql 查询并获得很好的响应。

我最近被告知我应该使用令牌设置一个 cookie,而不是在突变响应中返回它。所以我试图切换,但 cookie 不是由突变设置的。

server.js(节点)

import { GraphQLServer, PubSub } from 'graphql-yoga';
import {resolvers, fragmentReplacements} from './resolvers/index'
import prisma from './prisma'

const pubsub = new PubSub()

export default new GraphQLServer({
  typeDefs: './src/schema.graphql',
  resolvers,
  context(request) {
    return {
      pubsub,
      prisma,
      request, //fragmentReplacements[], request, response
    }
  },
  fragmentReplacements
});

Mutation.js(节点)

export default {
  async createUser(parent, args, {prisma, request}, info) {
    const lastActive = new Date().toISOString()
    const user = await prisma.mutation.createUser({ data: {...args.data, lastActive }})
    const token = generateToken(user.id)
    const options = {
      maxAge: 1000 * 60 * 60 * 24, //expires in a day
      // httpOnly: true, // cookie is only accessible by the server
      // secure: process.env.NODE_ENV === 'prod', // only transferred over https
      // sameSite: true, // only sent for requests to the same FQDN as the domain in the cookie
    }
    const cookie = request.response.cookie('token', token, options)
    console.log(cookie)
    return {user}
  },
  // more mutations...

控制台日志(cookie)

附加 cookie 的 console.log(cookie) 输出

index.js(反应)

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
import ApolloClient, { InMemoryCache, create } from 'apollo-boost';
import {ApolloProvider} from 'react-apollo'

const client = new ApolloClient({
  uri: 'http://localhost:4000',
  cache: new InMemoryCache(),
  credentials: 'include',
  request: async operation => {
    operation.setContext({
      fetchOptions: {
        credentials: 'same-origin'
      }
    })
  },
})

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>, 
  document.getElementById('root'));

所以我的问题是:

  1. 有没有更好的方法来使用 GraphQL 进行身份验证,或者在 auth 突变中使用 cookie 设置令牌是否合适?
  2. 假设这是一个不错的方法,我如何从突变中设置 cookie

谢谢你的时间!

标签: reactjscookiesgraphqlapolloprisma

解决方案


您需要在 ApolloClient 中包含凭据

 fetchOptions: {
    credentials: 'include'
 }

推荐阅读