reactjs - 如何使用 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 的 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'));
所以我的问题是:
- 有没有更好的方法来使用 GraphQL 进行身份验证,或者在 auth 突变中使用 cookie 设置令牌是否合适?
- 假设这是一个不错的方法,我如何从突变中设置 cookie?
谢谢你的时间!
解决方案
您需要在 ApolloClient 中包含凭据
fetchOptions: {
credentials: 'include'
}
推荐阅读
- javascript - 我正在尝试执行 Alexa 技能,但她说请求的技能响应有问题
- symfony - 在 Symfony 中扩展实体并继承关系
- php - 无法登录 Laravel Jetstream 应用程序
- python - 如何阻止表数据与熊猫、bs4、请求和制表重叠
- python - AsyncIO 任务循环未在线程内同时执行所有任务
- c# - 我无法在两个脚本之间进行通信
- html - 如何将图像放在 div 上,并将此图像从 div 响应中取出?
- snowflake-cloud-data-platform - ACCOUNT_USAGE.TABLES 视图具有 TABLE_OWNER AS NULL 的记录
- javascript - 从外部网络 php / jquery 将文件上传到共享点
- spring-boot - 如何在 Spring Boot 中使用 WebClient 配置 OAuthClient2Password