passport.js是Nodejs中的一個作登陸驗證的中間件,極其靈活和模塊化,而且可與Express、Sails等Web框架無縫集成。Passport功能單一,即只能作登陸驗證,但很是強大,支持本地帳號驗證和第三方帳號登陸驗證(OAuth和OpenID等),支持大多數Web網站和服務。html
具體詳解 W3Cschool 有詳細教程,這裏再也不贅述。 www.w3cschool.cn/passport_js…git
npm install passport-jwt複製代碼
(1)、配置策略 JWT認證策略的構造以下:github
new JwtStrategy(options, verify)複製代碼
參數: options 是包含用於控制如何從請求中提取令牌或者被驗證的選項的對象文本。web
public
編碼密鑰( 非對稱)的字符串或者緩衝區,用於驗證令牌的簽名。 除非提供 secretOrKeyProvider
,不然須要。function secretOrKeyProvider(request, rawJwtToken, done)
應該爲給定密鑰和請求組合調用一個密碼或者 done
編碼的public
密鑰( 非對稱)。 done
以 function done(err, secret)
格式接受參數。 除非提供 secretOrKey,不然須要。jwtFromRequest
( 必選) 函數 null
。 有關詳細信息,請參閱從請求列表中提取 JWT。["HS256","HS384"]
。true
,請求將被傳遞到驗證回調。 verify( req,jwt_payload,done_callback )
。passport-jwt
使用 jsonwebtoken
驗證令牌。 verify 是具備參數 verify(jwt_payload, done)的函數算法
(2) 從請求中提取 JWT 能夠將JWT包含在請求中的方法有多種。 爲了保持盡能夠能靈活,JWT從請求中解析爲 jwtFromRequest 參數傳遞的用戶回調。 從如今開始,這個回調將接受請求對象做爲參數,並返回編碼的JWT字符串或者 null。npm
passport-jwt.ExtractJwt 中提供了許多提取器工廠函數。 這些工廠函數返回一個使用給定參數配置的新抽取器。json
(3)編寫自定義提取程序函數 若是所提供的提取器不知足你的需求,你能夠輕鬆提供你本身的回調。 例如,若是使用cookie解析器中間件並想在cookie中提取 JWT,能夠使用如下函數做爲jwtFromRequest選項的參數:安全
var cookieExtractor = function(req) {
var token = null;
if (req && req.cookies) {
token = req.cookies['jwt'];
}
return token;
};複製代碼
(4) passport-local 策略實例markdown
const JwtStrategy = require('passport-jwt').Strategy
const ExtractJwt = require('passport-jwt').ExtractJwt
const User = require('../models/user')
const config = require('../config')
const opts = {
// Prepare the extractor from the header.
jwtFromRequest: ExtractJwt.fromExtractors([
req => req.cookies['authorization'],
ExtractJwt.fromUrlQueryParameter('access_token'),
ExtractJwt.fromAuthHeaderWithScheme('Bearer'),
]),
// Use the secret passed in which is loaded from the environment. This can be
// a certificate (loaded) or a HMAC key.
secretOrKey: config.JWT_SECRET,
// Verify the issuer.
issuer: config.JWT_ISSUER,
// Verify the audience.
audience: config.JWT_AUDIENCE,
// Enable only the HS256 algorithm.
algorithms: [config.JWT_ALG],
// Pass the request object back to the callback so we can attach the JWT to it.
passReqToCallback: true
}
module.exports = passport => {
passport.use(new JwtStrategy(opts, async function (req, jwt_payload, done) {
try {
const userInfo = await User.findOne({
user_uuid: jwt_payload.user_uuid
})
if (userInfo && userInfo.user_role > 0) {
done(null, userInfo)
} else {
done(null, false)
}
} catch (e) {
return done(e)
}
}))
}複製代碼
若是想繼續學習 JWT 請查看我另一篇文章: 全棧之初識JWT -- Web安全的守護神 若是想繼續學習 JWT && Passport 聯合應用 請查看我另一篇文章: 全棧之鑑權之旅 -- JWT + passport 實現 Token 驗證(Node + Express)cookie
本文由博客一文多發平臺 OpenWrite 發佈!