简体   繁体   English

在JWT中使用angularjs使用护照OAuth

[英]Using passport oauth in angularjs with JWT

Currently, I am working on an Angularjs website that uses JWT (json web tokens) to verify if someone is logged in or not. 目前,我正在使用JWT(json网络令牌)来验证是否有人登录的Angularjs网站上工作。 Now I am wanting to add some "one-click" login methods using passport / oauth but finding it difficult on how I can pass the login details back to angularjs. 现在,我想使用passport / oauth添加一些“一键式”登录方法,但是很难将登录详细信息传递回angularjs。

When I login with email / password, I generate a token, and pass it back to angular: 当我使用电子邮件/密码登录时,我生成一个令牌,并将其传递回angular:

var token = jwt.sign({ _id: user._id.toString() }, JWT_SECRET);
return res.json({
  userID: user._id.toString(),
  username: user.username,
  isAdmin: user.isAdmin,
  token: token
});

And the token is used to verify login. 令牌用于验证登录。 When going through oauth, you must leave the site, and then come back, so I can't just return some token from ajax the same way. 通过oauth时,您必须离开站点,然后再回来,所以我不能仅以相同的方式从ajax返回一些令牌。

I thought it might work to add it to my verify call (when someone refreshes the website, I run a check to see if they were logged in already). 我认为将其添加到我的验证呼叫中可能会起作用(当有人刷新网站时,我会进行检查以查看他们是否已登录)。 This checks for the token and returns the proper user data. 这将检查令牌并返回正确的用户数据。 Is there a way to check if passport is logged in already here as well? 有没有办法检查护照是否已经在这里登录? My verify code looks like this (JWT automagically sets the token info to req.user): 我的验证代码如下所示(JWT自动将令牌信息设置为req.user):

Schemas.User.findOne({ _id: req.user._id }, function (err, user) {
  if (err || !user) { return res.send(401); }
  return res.json({
    userID: user._id.toString(),
    username: user.username,
    isAdmin: user.isAdmin
  });
});

So I had a couple of issues. 所以我有几个问题。 I wasn't using passport properly (I had forgotten to add the serialize / deserialize). 我没有正确使用护照(我忘记添加序列化/反序列化)。 Then on my auth callback I set a cookie with a JWT in it (I also didn't realize that passport also set req.user automagically), and checked for the cookie in angular. 然后在我的auth回调中,我在其中设置了一个带有JWT的cookie(我也没有意识到护照也自动设置了req.user),并检查了cookie是否成角度。 If the cookie exists, I set it to local storage, and delete the cookie. 如果该cookie存在,则将其设置为本地存储,然后删除该cookie。 Works like a charm! 奇迹般有效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM