【问题标题】:How to use PassportJS with JWT in a REST API如何在 REST API 中使用 PassportJS 和 JWT
【发布时间】:2021-12-29 23:19:21
【问题描述】:

我目前正在构建一个 REST API,用户可以在其中通过不同的护照策略(googlefacebook)对自己进行身份验证。身份验证必须在没有会话的情况下完成。

现在我已经制定了本地策略,并且效果类似; 应用程序POST /login 到 API,然后当用户输入正确的凭据时,他们会像这样得到一些有效负载

[
    {
        "tokenType": "refresh",
        "expiresIn": 604800000,
        "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTUsImlhdCI6MTY0MDc4NzA4MCwiZXhwIjoxNjQxMzkxODgwfQ.zdxdpX8NkiSTsbZj0xOd18RdbLjeSsQpkikLGW71xrE"
    },
    {
        "tokenType": "access",
        "expiresIn": 7200000,
        "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTUsImlhdCI6MTY0MDc4NzA4MCwiZXhwIjoxNjQwNzk0MjgwfQ.EBDuJqQYT-D0bnYbC76_khe6b29c80R4pMyEaBNKLKE"
    }
]

但是,googlefacebook 策略的问题在于它们通过 OAuth 工作。在 OAuth 身份验证成功后,我正在努力寻找一种方法将上述信息(如我的本地策略)发送给客户端。

这些 OAuth 服务使用 /auth/facebook/return 之类的返回 URL。但是这个返回 URL 在 API 上,它不能将信息发送到客户端(或者可以吗?)。

我该怎么做?

【问题讨论】:

    标签: node.js rest oauth passport.js passport-facebook


    【解决方案1】:

    您可以使用passport-facebook-token,这与passport-facebook 完全不同。它确实提供了可用于对用户进行身份验证的令牌。

    passport.use('facebook-token', new FacebookTokenStrategy({
        clientID        : "your-client-id",
        clientSecret    : "secret"
      },
      function(accessToken, refreshToken, profile, done) {
        // console.log(profile);
    
         var user = {
            'email': profile.emails[0].value,
            'name' : profile.name.givenName + ' ' + profile.name.familyName,
            'id'   : profile.id,
            'token': accessToken
        }
    
        // You can perform any necessary actions with your user at this point,
        // e.g. internal verification against a users table,
        // creating new user entries, etc.
    
        return done(null, user); // the user object we just made gets passed to the route's controller as `req.user`
      }
    ));
    

    使用 passport.authenticate(),指定 'facebook-token' 策略来验证请求。您需要将其用作任何路由进行身份验证的中间件。

    app.post('/auth/facebook/token',
      passport.authenticate('facebook-token'),
      function (req, res) {
        // do something with req.user
        res.send(req.user? 200 : 401);
      }
    );
    
    

    我建议您检查this 链接和引擎盖下的code,这是有据可查的。

    【讨论】:

      猜你喜欢
      • 2021-08-16
      • 2019-11-02
      • 2018-11-24
      • 2014-09-21
      • 1970-01-01
      • 2020-10-09
      • 2016-02-23
      • 1970-01-01
      • 2015-06-16
      相关资源
      最近更新 更多