node.js - Node : Sending JSON Web token to client with page redirect

标签 node.js express jwt passport.js json-web-token

我正在使用 Node Express 构建我的后端服务器。此外,身份验证是我的应用程序使用 Passport-SAML 进行的。我正在使用 JWT 来维护用户 session 。 所以流程是,

  1. 用户调用登录端点
  2. 他们被重定向到 SAML 身份提供商。
  3. 提供商验证用户并发回授权 通过回调 URL 发送到服务器。
  4. 我正在使用 POST 回调 URL 进行身份验证,然后创建一个 用户执行授权和 session 管理的 token 。

回调 POST 端点也有一个页面重定向。到目前为止,我了解到的是 res.status 和 res.redirect 不能在同一个端点,原因很明显。我一直在努力寻找正确的方法,非常感谢任何帮助。

router.route('/login')

.get(
    passport.authenticate(config.passport.strategy,
      {
        successRedirect: '/',
        failureRedirect: '/login'
      })
);

router.route(config.passport.saml.path)

.post(
    passport.authenticate(config.passport.strategy,
      {
        failureRedirect: '/',
        failureFlash: true
      }),
    function (req, res) {
      res.redirect('/');
      var token = Verify.getToken(req.user.saml);
      return res.status(200).json({
        status: 'Login successful!',
        success: true,
        token: token
      });
      console.log(token,'yes');

    }
);

最佳答案

这里有一系列选项

Cookie

res.cookie('token', token, ...);
res.redirect(...);

网址参数

res.redirect(`/some/url?token=${token}`);

自定义 header

res.set('x-token', token);
res.redirect(...);

关于node.js - Node : Sending JSON Web token to client with page redirect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45882530/

相关文章:

node.js - 隐藏相关模型的方法

node.js - 如何修复 'Content Security Policy: The page’ s 设置阻止在 http ://localhost:8080/favicon. ico (“default-src” 处加载资源。'

php - 从 PHP 发送请求到 Node.js

node.js - 如何使用 JWT 将 key 从前端( Angular 4)传递到后端( Node js)

node.js - console.log 和 process._rawDebug 之间的区别

node.js - 从 2 个 mongodb 集合搜索后的 Nodejs 单个回调

node.js - 如何使用nodejs从密码查询中获取对象?

javascript - POST 数组数据到 Express 被解析为 JSON

javascript - node/mongo/functions/scoping 的奇怪行为

javascript - 将 Nestjs 与 Cognito 集成