This API is an example of a simple authentication service using node.js
Tools for the job:
- Koa.js
- Passport.js
- JWT
The robust and simple framework for serving and handling web requests through async middleware. There's nothing particular about it for a given task of building authentication API service. Minimal overhead provides great transparency and control over implementation. Both perfect for security sensitive application like auth API and demonstrating decisions in a code challenge.
This library will provide convenient middleware for Koa to handle authentication throughout request lifecycle and cleanly separate concerns between app server, auth middleware and router middleware. It exposes single internal API for building any authentication strategy, which makes this implementation more conventional and extendable.
Signed tokens' claims can be verified at the edge without DB roundtrip and used with multiple backends as it can carry both session data and authenticity proof. JWT is convenient to work with in web front- and backends.
This implementation uses a single JWT token. However in certain projects with requirements calling for stricter, more complex auth flow and/or sliding-sessions it makes sense to use separate refresh
and access
tokens: refresh
token for auth server reissuing access
tokens while making blacklist or other checks and access
tokens for per-resource access and tracking session.
npm ci
- Installing dependencies
npm start
- Run service at port 3000
by default or defined in PORT
environment variable
PORT
- Serve app on this port. 3000
by default.
JWT_SECRET
- Secret used to sign and verify JWT token. secret
by default.
JWT_EXPIRES_IN
- Lifetime of token in zeit/ms compatible format. 30 days
by default.
name: user
password: 123
Routes requiring authentication accept token in Authorization
header with Bearer
prefix.
Invalid token response:
401
Unauthorized
POST /auth/login
200
{
"token": "a.b.c",
"expires_in": "30 days" // zeit/ms format
}
POST /auth/refresh
Authorization: Bearer ${JWT}
{
"token": "a.b.c",
"expires_in": "30 days" // zeit/ms format
}
GET /data/public
This is a publicly available data
GET /data/private
Authorization: Bearer ${JWT}
This is a secret available only to a few chosen