koa-simple-oauth
Simple OAuth2 authentication middleware for Koa. Internally uses simple-oauth2 and Node Fetch API.
Requirements
Installation
yarn add koa-simple-oauth
Usage
Requirements
import Koa from 'koa';
import session from 'koa-session';
import simpleOauth from 'koa-simple-oauth';
const app = new Koa();
app.keys = ['secretSessionKey'];
const sessionConfig = {};
app.use(session(sessionConfig, app));
Configuration
const oauthConfig = {
clientId: 'abcdefgh1234',
clientSecret: '5678mnopqrst',
url: 'https://oauth.example.com/api/v1',
redirectUrl: 'https://myapp.example.com/api/v1/oauth/authorized',
userUrl: 'https://oauth.example.com/api/v1/me',
userMethod: 'GET',
user: (data) => {
const user = data.user;
if (!user.isAdmin) {
return 'not_admin';
}
return user;
},
oauthOptions: {},
redirectSuccessUrl: 'https://myapp.example.com/login/success',
redirectErrorUrl: 'https://myapp.example.com/login/error',
disableErrorReason: false,
onSuccess: (ctx, data, status = 200) => {
ctx.status = status;
ctx.body = typeof data === 'object' ? JSON.stringify(data) : data;
},
onError: (ctx, status, message, err) => {
ctx.status = status;
ctx.body = `${message}: ${err.message}`;
},
logError: (err) => {
if (err.message !== 'Not logged in') {
console.error(err);
}
},
routes: {
login: '/login',
authorized: '/authorized',
whoami: '/whoami',
logout: '/logout'
}
};
With Koa Router (recommended)
import Router from 'koa-router';
const router = new Router();
simpleOauth(oauthConfig, router);
app.use(router.routes());
app.use(router.allowedMethods());
With Koa Mount
import mount from 'koa-mount';
const oauthMiddleware = simpleOauth(oauthConfig);
const {login, authorized, whoami, logout} = oauthMiddleware;
app.use(mount('/login', login));
app.use(mount('/authorized', authorized));
app.use(mount('/whoami', whoami));
app.use(mount('/logout', logout));
With Koa Route
import _ from 'koa-route';
const oauthMiddleware = simpleOauth(oauthConfig, _);
const {login, authorized, whoami, logout} = oauthMiddleware;
app.use(login);
app.use(authorized);
app.use(whoami);
app.use(logout);
Object.values(oauthMiddleware).forEach((middleware) => {
app.use(middleware);
});