client (axios)
yarn add jsonwebtoken
Sample code
import axios from 'axios';
import jwt from 'jsonwebtoken';
const dataReceiver = axios.create({
baseURL: 'http://localhost:3200/',
timeout: 3 * 1000,
});
const secret = 'your_secret';
// Add a request interceptor
dataReceiver.interceptors.request.use(function (config) {
let payload = { hello: 'world' };
config.headers.Authorization = 'Bearer ' + jwt.sign(payload, secret, { expiresIn: 5 * 60 });
return config;
});
export { dataReceiver };
server (koa)
yarn add koa-jwt
import config from 'config';
import http from 'http';
import Koa from 'koa';
import koaBody from 'koa-body';
import koaLogger from 'koa-logger';
import jwt from 'koa-jwt';
import router from './router';
const app = new Koa()
.use(jwt({ secret: 'your_secret' }))
.use(koaBody())
.use(koaLogger())
.use(router.routes())
.use(router.allowedMethods());
const HTTP_SERVER_PORT = config.get('server.port');
const httpServer = http.createServer(app.callback());
async function start() {
httpServer.listen(HTTP_SERVER_PORT);
}
start();
References
- jwt https://jwt.io/introduction
- npm jsonwebtoken https://www.npmjs.com/package/jsonwebtoken
- koa-jwt https://github.com/koajs/jwt