jwt-koa
Simple mini-lib for secured APIs and servers with Koa and JWT.
What includes
- Middleware for checking request headers for token
- CreateToken function for creating token
Setup
Install it:
npm install jwt-koa --save
or
yarn add jwt-koa
Usage
Import
const jwtKoa = require('jwt-koa');
Set secret key for JWT
process.env.secret = 'SECRET';
Set middleware to secured Router
securedRouter.use(jwtKoa.middleware);
securedRouter.get('/secured', async ctx => {
ctx.body = { data: 'Secured Data' };
});
Send token to client
notSecuredRouter.post('/send', async ctx => {
const token = jwtKoa.createToken({ tokenData: 'tokenData' });
const tokenWithExpireTime = jwtKoa.createToken(
{ tokenData: 'tokenData' },
5000
);
ctx.response.body = token;
});
Client-side example
fetch('/secured', { method: 'GET', headers: { Authorization: } })
.then(j => j.json())
.then(data => );