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 发布!