【问题标题】:Getting Access token validity获取访问令牌有效性
【发布时间】:2019-05-27 08:55:12
【问题描述】:

我正在使用护照验证用户进入我的应用程序

我已经为此创建了护照策略

passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL:  process.env.GOOGLE_CALLBACK_URL,
    userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
    accessType: 'offline'
  }, (accessToken, refreshToken, profile, cb) => {
       console.log(refreshToken)
        let profileSort = extractProfile(profile)
         mongooeHelperFunction.findUserByEmail(profileSort.email).then(response => {
           if (!response) {
            mongooeHelperFunction.createNewUser(profileSort)
            .then(res => { 
               let newRes = {...res}
                newRes["accessToken"] = accessToken
                cb(null, newRes)
            })
            .catch(error => {  throw error  })
           } else {
                let newRes = {...response}
                newRes["accessToken"] = accessToken
                cb(null, newRes)
           }
        })
        .catch(error => {  throw error  })
    }
))

(上面和我们平时创建的护照策略很相似)

为了获得上面的刷新令牌,我在我的 api 路由中这样做

router.get("/google",  passport.authenticate('google', {accessType: 'offline', prompt: 'consent', scope: ['profile', 'email',  'https://mail.google.com/' ] }));

问题:这确实给了我一个访问令牌。我如何知道访问令牌何时到期?

我最初的目标是在访问令牌过期时通过刷新令牌获取新的访问令牌。

谁能帮我实现这个目标?

【问题讨论】:

    标签: node.js express oauth-2.0 jwt passport.js


    【解决方案1】:

    OAuth 令牌以加密格式包含其中的所有信息。它们是 JWT 令牌的一种形式,您可以轻松解密您的令牌 here

    出于编程目的,您可以使用 npm pakcages 解析 JWT。 Auth0 是最好的实现之一,它应该可以帮助您避免编写手动解密算法。

    【讨论】:

      【解决方案2】:

      要添加到上述答案,oauth2 jwt 令牌编码未加密,因此您可以通过解码令牌轻松读取到期时间。 使用标准 jwt 库有两种常用方法来验证令牌是否已过期。我用https://www.npmjs.com/package/jsonwebtoken

      假设您拥有公钥或密钥,请使用 verify 方法检查令牌是否已过期。如果您使用的是过期令牌,则会引发错误。

      var jwt = require('jsonwebtoken');
      var token ='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpYXQiOjE1NDYzOTYxMDYsImV4cCI6MTU0NjM5NjEwN30.qFeaKny2Ruk7ZeZsHGpPcw6aksyZHUfDOmb6EvgiGIo';
      var verified = jwt.verify(token, 'secret');
      

      使用 decode 方法对令牌进行解码。您可以从解码对象中的 exp 字段中获取到期时间

      var jwt = require('jsonwebtoken');
      var token ='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpYXQiOjE1NDYzOTYxMDYsImV4cCI6MTU0NjM5NjEwN30.qFeaKny2Ruk7ZeZsHGpPcw6aksyZHUfDOmb6EvgiGIo';
      var decoded = jwt.decode(token);
      console.log('Expiry timestamp----------->', decoded.exp);
      

      此外,为了测试这一点,请确保您在创建 JWT 时设置到期时间

      var jwt = require('jsonwebtoken');
      var token = jwt.sign({ foo: 'bar' }, 'secret', {expiresIn: '1h'});
      

      您可以在此处阅读有关 JWT 的更多信息https://jwt.io/introduction/

      【讨论】:

        猜你喜欢
        • 2012-12-28
        • 1970-01-01
        • 1970-01-01
        • 2017-08-31
        • 1970-01-01
        • 2014-07-09
        相关资源
        最近更新 更多