Getting started with @node-oauth/oauth2-server
Preface
This library implements the OAuth 2.0 standard but leaves room to custom implementation details where the standard is either vague or explicitly states, if a detail is up to the implementation.
Therefore, getting familiar with the several RFCs is fundamental for understanding the standard and for a correct implementation.
We highly encourage you to read the following resources, before starting to operate your own authorization server:
- RFC 6749 - The OAuth 2.0 Authorization Framework
- RFC 6750 - Bearer Tokens
- RFC 6819 - Threat Model and Security Considerations
- RFC 7009 - Token Revocation
- RFC 7636 - Proof Key for Code Exchange (PKCE)
- RFC 9700 - Best Current Practice for OAuth 2.0 Security
- OWASP OAuth2 cheatsheet
Features
- Supports
authorization code,client credentials,refresh tokenandpassword(deprecated) grant, as well asextension grants, with scopes. - Can be used with promises, ES6 generators and async/await.
- Fully
6749and6750compliant. - Implicitly supports any form of storage, e.g. PostgreSQL, MySQL, MongoDB, Redis, etc.
- Complete test suite.
Installation
This module is developed for Node.js and you can install this package using npm via
npm install --save @node-oauth/oauth2-serverPlease note, that we still provide this library in "classic" commonjs format with a pretty low node version requirement for maximum backwards compatibility. A future esm release is planned. We also highly encourage you to use supported/maintained Node.js versions.
Usage
The @node-oauth/oauth2-server module is framework-agnostic but there are several officially supported adapters available for popular HTTP server frameworks such as Express and Koa. If you're using one of those frameworks it is strongly recommended to use the respective adapter module instead of rolling your own.
Consider the following minimal example, which you can use as a foundation for further development:
const OAuth2Server = require('@node-oauth/oauth2-server');
const Request = OAuth2Server.Request;
const Response = OAuth2Server.Response;
const model = require('./model');
const oauth = new OAuth2Server({model});
let request = new Request({
method: 'GET',
query: {},
headers: {Authorization: 'Bearer foobar'}
});
let response = new Response({
headers: {}
});
oauth.authenticate(request, response)
.then((token) => {
// The request was successfully authenticated.
})
.catch((err) => {
// The request failed authentication.
});The most crucial part in this setup is the model. It acts as the bridge between the OAuth2 server library and your system.
As a rule of thumb, the library handles the overall OAuth2 workflows, while you can leverage the
modelto implement storage locations (In-Memory, DB, Caching) and client management.
Note, that different workflows require different models. Read the model overview of what is required for the model in context of specific grant types.