GraphQL发行JWT/Cookie [英] GraphQL issuing JWT/Cookie

查看:81
本文介绍了GraphQL发行JWT/Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将React用作前端,将REST API用作后端,我的REST仅发布HTTP我存储在前端并在每个REST请求中使用的Cookie,例如代码 Atlassian JIRA拥有这样的身份验证,现在我想将该解决方案从REST迁移到GraphQL,如果GraphQL方面的授权已解决问题(只有Apollo拥有Cookie和JWT身份验证机制,更不用说本机实现了),我仍然不知道如何从GraphQL端发出Cookie/JWT.

I am using React as frontend and REST API as backend, my REST is issuing http only Cookie what i am storing on frontend and using on every REST request, for example of code, Atlassian JIRA have auth like that , now i want to migrate that solution from REST to GraphQL, and if authorisation on GraphQL side is already solved problem (only Apollo have both Cookie and JWT auth mechanisms, not to mention native implementations), i still can't figure out how to issue Cookie/JWT from GraphQL side.

是否可以从GraphQL向我提供cookie?问题是GraphQL如何在客户端上设置新的cookie?像set-cookie标头这样的东西可能吗?

Is there possibility to provide me cookie from GraphQL at all? Question is how GraphQL can set new cookie on client? Is something like set-cookie header possible?

推荐答案

如果要避免使用单独的身份验证终结点,而是希望能够向GraphQL终结点发送变异并生成授权cookie,则可以您将需要修改在服务器上设置GraphQL端点的方式.

If you want to avoid having a separate authentication endpoint and instead want to be able to send a mutation to your GraphQL endpoint and have that generate the authorization cookie, you'll need to modify how you set up your GraphQL endpoint on the server.

在使用 express-graphql apollo-server-express 时,默认情况下,您的请求对象将作为上下文传递给解析器.为了获取响应对象,您必须像这样包装端点:

When using express-graphql or apollo-server-express, your request object is passed to your resolvers as the context by default. In order to get your response object, you have to wrap your endpoint like this:

app.use('/graphql', (req, res) => {
  return graphqlHTTP({
    schema,
    context: { req, res },
  })(req, res);
);

在该突变的解析程序中,您可以使用 res.cookie()设置cookie.

Within the resolver for that mutation, you can then set the cookie using res.cookie().

以这种方式处理事情可能会很痛苦-您可能希望利用一个或多个单独的端点进行身份验证,这将使您可以利用像 passport 这样的库来进行繁重的工作.

Handling things this way can be a pain, though -- you may want to utilize one or more separate endpoints for authentication, which would allow you to utilize libraries like passport to do the heavy lifting.

这篇关于GraphQL发行JWT/Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆