6.2.0 • Published 3 years ago
@waiting/egg-jwt v6.2.0
egg-jwt
jwt siging, verifying and authentication for midway/egg framework.
Installation
npm install @waiting/egg-jwt
Configuration
Enable Plugin
Edit ${app_root}/src/config/plugin.ts
:
export const jwt = {
enable: true,
package: '@waiting/egg-jwt',
}
Add Configurations
/* location: ${app_root}/src/config/config.${env}.ts */
import { JwtEggConfig } from '@waiting/egg-jwt'
export const jwt: JwtEggConfig = {
agent: false,
enable: true, // enable middleware
client: {
debug: false,
secret: '123456abc',
},
// https://github.com/eggjs/egg-path-matching
ignore: ['/signup', '/login'],
}
Usage
import { Provide, Plugin } from '@midwayjs/decorator'
import { Jwt } from '@waiting/egg-jwt'
import assert from 'assert'
@provide()
export class UserService {
constructor(
@plugin() private readonly jwt: Jwt,
) { }
@get('/siginup')
public signup(ctx: Context) {
const payload = { foo: 'bar', iat: 1566629919 }
const token = this.jwt.sign(payload)
const valid = this.jwt.verify(token)
assert.deepStrictEqual(valid, payload)
ctx.body = `\nToken: ${token}`
}
@get('/')
public index(ctx: Context): void {
ctx.body = `\nPayload: ${ctx.jwtState && ctx.jwtState.user ? JSON.stringify(ctx.jwtState.user) : 'Not found'}`
}
}
Then:
curl -I 127.0.0.1:7001
// response HTTP/1.1 401 Unauthorized
curl 127.0.0.1:7001/signup
// response ends with signature 'PZkACzct30IcrymoodYlW0LW0Fc1r6Hs1l8yOZSeNpk'
curl 127.0.0.1:7001/ \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpYXQiOjE1NjY2Mjk5MTl9.PZkACzct30IcrymoodYlW0LW0Fc1r6Hs1l8yOZSeNpk"
// response payload: {"foo":"bar","iat":1566629919}