node.js - 如何将 Passport.js 中的 token 存储在本地存储中

标签 node.js angular express

我正在尝试将从 Passport.js 返回的 jwt token 存储在浏览器 localStorage 中,由于 token 是从服务器生成的,因此从服务器到客户端的通信遇到了一些问题。

对于如何在客户端浏览器 localStorage 上设置服务器生成的 token 的任何帮助,我将不胜感激。

路线

  // Setting the github oauth routes
  app.get('/auth/github', passport.authenticate('github', {
    failureRedirect: '/signin'
  }), authCallback);

  app.get('/auth/github/callback', passport.authenticate('github', {
    failureRedirect: '/signin'
  }), authCallback);

passport.js

  passport.use(new GitHubStrategy(
    {
  clientID: process.env.GITHUB_CLIENT_ID || config.github.clientID,
  clientSecret: process.env.GITHUB_CLIENT_SECRET || config.github.clientSecret,
  callbackURL: config.github.callbackURL
},
((accessToken, refreshToken, profile, done) => {
  User.findOne({
    'github.id': profile.id
  }, (err, user) => {
    if (err) {
      return done(err);
    }
    if (!user) {
      user = new User({
        name: profile.displayName,
        username: profile.username,
        provider: 'github',
        github: profile._json
      });
      user.save(() => done(err, user));
    } else {
      return done(err, user);
       }
      });
    })
  ));

AuthCallBack

export const authCallback = (req, res) => {
  const { TOKEN_SECRET } = process.env;
  if (!req.user) {
    res.redirect('/#!/signin?error=emailRequired');
  } else {
    const token = jwt.sign(
      { user: req.user.id, name: req.user.name },
      TOKEN_SECRET,
      { expiresIn: 72 * 60 * 60 }
    );
    // window.localStorage.setItem('token', token);
    res.redirect('/#!/app');
  }
};

如果您能帮助我将来自 authCallBack 的 token 存储在我的浏览器 localStorage 中,我将不胜感激。

最佳答案

我必须通过在浏览器 cookie 中设置数据,然后检索客户端中存储的数据,然后将数据存储在浏览器 localStorage 中来解决此问题。

关于node.js - 如何将 Passport.js 中的 token 存储在本地存储中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46452290/

相关文章:

javascript - 如何在 Node.js 中创建 Get 请求以从 json 获取特定对象?

node.js - 从嵌套回调而不是父函数返回值

angular - 为什么 Angular 的英雄之旅 http 错误处理程序接受任何类型的参数?

node.js - Express JS 相当于 Python 框架中的装饰器模式

node.js - sqlite/sequelize 中 hasOne 和 hasMany 的表示

jquery - 如何在 Electron 中使用 fs 保存 PDF 文件?

angular - 在 stackblitz Angular 项目上找不到文件

angular - Angular 4 中的树结构

node.js - 对 Node.js 模块使用单例方法

node.js - 如果 Node 关闭,如何在多个 Node 上处理 socketio