- http 是無狀態(tài)協(xié)議。
- 訪問一個服務(wù)器,不可能攜帶cookie。 必須是服務(wù)器得到這次請求,在下行響應(yīng)報頭中,攜帶cookie信息,此后每一次瀏覽器往這個服務(wù)器發(fā)出的請求,都會攜帶這個cookie
ctx.cookies.set(name, value, [options])
- 通過options 設(shè)置cookie name 的value
ctx.cookies.get('name')
Usage 用法
JWT 身份驗證中間件使用jwt令牌 來驗證使用者身份,如果令牌是有效的,則在ctx.state.user(默認) 將設(shè)置被解密JSON,用作稍后的中間件授權(quán)和訪問控制
Retrieving the token 檢索令牌
三種方法
- 令牌默認是http請求頭部中的Authorization提供的。
- 它還可以由在opts.cookie 中設(shè)置的cookie提供。
- 自定義令牌檢索 由opts.getToken 選項提供
令牌的解析順序
3->2->1
- opts.getToken [function]
- check the cookies [??if opts.cookie is set]
- check the Authorization header for a bearer token
Passing the secret
Checking if the token is revoked 檢測令牌是否已撤銷
opts.isRevoked
處理 鑒權(quán)失敗情況
if you don't want to expose koa-jwt errors to users
app.use( (ctx, next) => {
return next().catch((err) => {
if(err.status === 401) {
ctx.body = 'Protected resource, use Authorization header to get access\n aaa'
}
})
})
- 如果您更喜歡使用另一個ctx密鑰來解碼數(shù)據(jù),只需傳入密鑰 key
設(shè)置密鑰key (我的理解,重命名key值 ,看源碼后發(fā)現(xiàn)果然如此)
jwt({
secret: 'uid',
key: 'jwtdata'
})
// 獲取
ctx.state.jwtdata
// { uid: 111, exp: 1540368721, iat: 1540368667}
- 可以指定issuer
jwt({
secret: ['shared-secret', 'new-shared-secret'],
audience: 'http://myapi/protected',
issuer: 'http://issuer'
})