Introduction to Koa JWT
koa-jwt
is a middleware for Koa, a popular Node.js framework, that facilitates JSON Web Token (JWT) authentication. It provides a simple and effective way to secure your Koa applications by ensuring that requests are authenticated.
Installation
npm install koa-jwt jsonwebtoken
Basic Usage
Here’s a simple example of how to use koa-jwt
in a Koa application:
const Koa = require('koa');
const jwt = require('koa-jwt');
const jsonwebtoken = require('jsonwebtoken');
const app = new Koa();
const secret = 'shared-secret';
app.use(jwt({ secret }).unless({ path: [/^\/public/] }));
app.use(async (ctx, next) => {
if (ctx.url.match(/^\/public/)) {
ctx.body = 'This is a public endpoint!';
} else {
ctx.body = 'Private endpoint, user authenticated!';
}
});
app.listen(3000);
console.log('Server running on port 3000');
API Endpoints and Examples
Generating a Token
Use the jsonwebtoken
library to generate a token:
const token = jsonwebtoken.sign({ user: 'username' }, secret, { expiresIn: '1h' });
console.log(token);
Securing Routes
Protect your routes by using the koa-jwt
middleware:
app.use(jwt({ secret }).unless({ path: [/^\/public/] }));
Error Handling
Handle token verification errors in your application:
app.use(async (ctx, next) => {
return next().catch((err) => {
if (err.status === 401) {
ctx.status = 401;
ctx.body = 'Protected resource, use Authorization header to get access\n';
} else {
throw err;
}
});
});
Complete Application Example
const Koa = require('koa');
const jwt = require('koa-jwt');
const jsonwebtoken = require('jsonwebtoken');
const app = new Koa();
const secret = 'shared-secret';
app.use(jwt({ secret }).unless({ path: [/^\/public/] }));
app.use(async (ctx, next) => {
if (ctx.url.match(/^\/public/)) {
ctx.body = 'This is a public endpoint!';
} else if (ctx.url.match(/^\/login/)) {
const token = jsonwebtoken.sign({ user: 'username' }, secret, { expiresIn: '1h' });
ctx.body = { token };
} else {
ctx.body = 'Private endpoint, user authenticated!';
}
});
app.listen(3000);
console.log('Server running on port 3000');
This basic example sets up a Koa server with JWT authentication. The /public
endpoint is accessible without authentication, while the other routes require a valid JWT.
Conclusion
koa-jwt
is an excellent tool for adding authentication to your Koa applications. By understanding and utilizing its capabilities, you can secure your endpoints effectively and build robust Node.js applications.
Hash: 77a64ab2dea833701190f94ae75e32ced316521b17c48e127b03ecdff16a3b98