简介
-
koa-jwt
主要提供路有权限控制的功能,它会对需要限制的资源请求进行检查 -
token
默认被携带在Headers 中的名为Authorization的键值对中,koa-jwt
也是在该位置获取token
的 -
也可以使用Cookie来提供令牌
-
app.use(jwt( { secret: 'shared-secret', passthrough:true }))
通过添加一个passthrough
选项来保证始终传递到下一个(中间件) -
app.use(jwt({ secret: 'shared-secret', key: 'jwtdata' }))
可以使用另外一ctx key
来表示解码数据,然后就可以通过ctx.state.jwtdata
代替ctx.state.user
获得解码数据 -
secret
的值可以使用函数代替,以此产生动态的加密秘钥 -
koa-jwt
依赖于jsonwebtoken
和koa-unless
两个库的
koa-jwt 示例
- 示例中使用了
jwt-simple
,也可以选择使jsonwebtoken
const Koa = require('koa')
const Router = require('koa-router')
const jwt = require('jwt-simple')
const koaBody = require('koa-body')
const koaJwt = require('koa-jwt') //路由权限控制
const app = new Koa()
const router = new Router()
//秘钥
const jwtSecret = 'jwtSecret'
const tokenExpiresTime = 1000 * 60 * 60 * 24 * 7
// Custom 401 handling if you don't want to expose koa-jwt errors to users
app.use(function(ctx, next){
return next().catch((err) => {
if (401 == err.status) {
ctx.status = 401;
ctx.body = 'Protected resource, use Authorization header to get access\n';
} else {
throw err;
}
});
});
app.use(koaJwt({secret:jwtSecret}).unless({
path:[/^\/login/]
}))
router.get('/', (ctx) => {
ctx.body = 'Hello koa-jwt'
})
// router.use(koaJwt(jwtSecret).unless({
// path:[/^\/login/]
// }))
router.post('/login', koaBody(), (ctx) => {
const user = ctx.request.body
if (user && user.name){
let payload = {
exp:Date.now() + tokenExpiresTime,
name:user.name
}
let token = jwt.encode(payload, jwtSecret)
ctx.body = {
user:user.name,
code:1,
token
}
}else {
ctx.body = {
code:-1
}
}
})
// router.use(koaJwt(jwtSecret))
router.get('/userInfo', ctx => {
let token = ctx.header.authorization
ctx.body = {
token:token,
user:ctx.state.user
}
//使用jwt-simple自行解析数据
let payload = jwt.decode(token.split(' ')[1], jwtSecret);
console.log(payload)
})
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(3000, () => {
console.log('app listening 3000...')
})
image.png
image.png
option
- 可以直接参照源码设置
// Type definitions for koa-jwt 2.x
// Project: https://github.com/koajs/jwt
// Definitions by: Bruno Krebs <https://github.com/brunokrebs/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import Koa = require('koa');
export = jwt;
declare function jwt(options: jwt.Options): jwt.Middleware;
declare namespace jwt {
export interface Options {
secret: string | Buffer;
key?: string;
tokenKey?: string;
getToken?(opts: jwt.Options): string;
isRevoked?(ctx: Koa.Context, decodedToken: object, token: string): Promise<boolean>;
passthrough?: boolean;
cookie?: string;
debug?: boolean;
audience?: string;
issuer?: string;
algorithms?: string[];
}
export interface Middleware extends Koa.Middleware {
unless(params?: any): any;
}
}
网友评论