【发布时间】:2021-11-02 12:50:03
【问题描述】:
我已将我的 Apollo 客户端和服务器配置为使用 cookie:
客户:
const httpLink = createHttpLink({
uri: 'http://localhost:9090/graphql',
credentials: 'include',
});
const cache = new InMemoryCache();
const client = new ApolloClient({
link: httpLink,
cache,
});
服务器:
const app = express();
const server = new ApolloServer({
resolvers,
typeDefs,
context: async ({req, res}) => ({
req,
res,
prisma,
}),
});
await server.start();
const corsOptions = {
origin: 'http://localhost:8080',
credentials: true,
};
app.use(cors(corsOptions));
app.use(express.urlencoded({
extended: true,
}));
server.applyMiddleware({
app, cors: corsOptions,
});
app.listen({port: 9090}, () =>
console.log(`???? Server ready at http://localhost:9090${server.graphqlPath}`),
);
登录解析器:
loginUser: async (_, args, {req, res}) => {
const theUser = await prisma.user.findUnique({
where: {email: String(args.email)},
});
if (!theUser) throw new Error('Unable to Login');
const isMatch = bcrypt.compareSync(args.password, theUser.password);
if (!isMatch) throw new Error('Unable to Login');
const token = jwt.sign(theUser, 'supersecret');
res.cookie('id', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 1000 * 60 * 60 * 24 * 7,
});
return true;
},
当我登录我的 React 应用程序时,服务器会按预期设置一个 cookie,但我不确定如何使用该客户端 cookie 在服务器中验证我的用户以及如何保持登录状态。 cookie 也会添加到请求中。
这是一个仅限 http 的 cookie,所以我不能在客户端使用 cookie 信息。所以我想我需要一个函数来在每次加载应用程序时查询登录突变,然后在服务器上我可以检查请求,如果它在请求 cookie 中有 JWT 令牌,我可以对用户进行身份验证。
但我希望得到有关这种方法的一些反馈。
【问题讨论】:
标签: authentication cookies jwt apollo