如何使用Apollo从GraphQL Mutation设置Auth令牌cookie

时间:2019-04-01 00:55:50

标签: reactjs cookies graphql apollo prisma

我正在使用来自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...

console.log(cookie)

console.log(cookie)输出并附加了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

感谢您的时间!

1 个答案:

答案 0 :(得分:1)

您需要在ApolloClient中包含凭据

 fetchOptions: {
    credentials: 'include'
 }