JWT Redis Session for Koa 2
Pure JWT implementation using Redis as session storage for Koa 2, without any cookies
Quick Start
As middleware:
const koa = bodyParser = session = // import session from 'koa2-jwt-redis-session' const app = app app // If using import// app.use(session()) app app
As a function:
// After used as middleware// Somewhere when using as backdore let openDoorHandler = async { let userObj = account: 'sneaky' password: 'open_the_back_door'; let token = await ; ctxbody = token; // Token is in JSON format: {token: ..... , expiresIn: 3600} // expiresIn is the expire time in seconds, default is 3600} let guardHandler = async { let user = await ; if user != undefined ctxbody = user; else ctx; }
Options
When creating session instance, you can pass in an option object
const sessionOptions = // ......app // If using importapp
Here is the default option values
jwt: contentType: 'application/json' charset: 'utf-8' secret: 'koa2-jwt-redis-session' + authPath: '/authorize' registerPath: '/register' refreshTokenPath: '/refreshToken' expiresIn: 3600 accountKey: 'account' passwordKey: 'password' { if account && password let user = {}; useraccountKey = account; return user; else return false; } { if account && password let user = {}; useraccountKey = account; return user; else return false; } session: sessionKey: 'session' sidKey: 'koa:sess' redis: port: 6379 host: '127.0.0.1' db: 0 ttl: 3600 options: {}
Action flow
- Anonymous client post JSON user credential information
{ account: "...", password: "..." }
to/register
to register an account, - or post to
/authorize
to get authorization - Client get token in JSON like
{ token: "...", expiresIn: 3600 }
, or an401
error if not authorized - From then on, client send every request by the http header:
Authorization: Bearer <token>
, - or client would get
401
error if not authorized or token expired - On the server side, afterward middlewares can operate
ctx.session
as will