[英]Getting Access token validity
我正在使用護照來驗證用戶進入我的應用程序
我已經為同一人創建了護照策略
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/' ] }));
問題:這確實給了我一個訪問令牌。 我怎么知道訪問令牌何時到期?
我的最初目標是每當訪問令牌過期時都通過刷新令牌獲取新的訪問令牌。
誰能幫我實現這個目標?
要添加到上述答案中,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');
使用解碼方法對令牌進行解碼。 您可以從已解碼對象中的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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.