Skip to main content

ts-oauth2-server

A Node.js OAuth 2.0 Server in TypeScript that is standards compliant, utilizes JWT and Proof Key for Code Exchange (PKCE)

Contributors

Sponsors

Install

pnpm add @jmondi/oauth2-server

Entities and Repositories

// entities/client_entity.ts
import { OAuthClient, GrantIdentifier } from "@jmondi/oauth2-server";
import { ScopeEntity } from "./scope_entity";

class ClientEntity implements OAuthClient {
readonly id: string;
name: string;
secret: string | null;
redirectUris: string[];
allowedGrants: GrantIdentifier[];
scopes: ScopeEntity[];
createdAt: Date;
updatedAt: Date | null;
}
// entities/user_entity.ts
import { OAuthUser } from "@jmondi/oauth2-server";

export class User implements OAuthUser {
readonly id: string;
email: string;
passwordHash: string | null;
tokenVersion = 0;
lastLoginAt: Date | null;
createdAt: Date;
updatedAt: Date | null;
}
// repositories/client_repository.ts
import { PrismaClient } from "@prisma/client";
import { GrantIdentifier, OAuthClient, OAuthClientRepository } from "@jmondi/oauth2-server";

import { Client } from "../entities/client.js";

export class ClientRepository implements OAuthClientRepository {
constructor(private readonly prisma: PrismaClient) {
}

async getByIdentifier(clientId: string): Promise<Client> {
return await this.prisma.oAuthClient.findUniqueOrThrow({
where: {
id: clientId,
},
include: {
scopes: true,
},
});
}

async isClientValid(
grantType: GrantIdentifier,
client: OAuthClient,
clientSecret?: string,
): Promise<boolean> {
// implement me (see examples)
}
}

The Authorization Server

// services/authorization_server.ts
const authorizationServer = new AuthorizationServer(
clientRepository,
accessTokenRepository,
scopeRepository,
"secret-key",
);

authorizationServer.enableGrantType("client_credentials");
authorizationServer.enableGrantType({
grant: "authorization_code",
userRepository,
authorizationCodeRepository,
});
// other grant types you want to enable

Which Grant?

+-------+
| Start |
+-------+
V
|
+------------------------+ +-----------------------+
| Have a refresh token? |>----Yes----->| Refresh Token Grant |
+------------------------+ +-----------------------+
V
|
No
|
+---------------------+
| Who is the | +--------------------------+
| Access token owner? |>---A Machine---->| Client Credentials Grant |
+---------------------+ +--------------------------+
V
|
|
A User
|
|
+----------------------+
| What type of client? |
+----------------------+
|
| +---------------------------+
|>-----------Server App---------->| Auth Code Grant with PKCE |
| +---------------------------+
|
| +---------------------------+
|>-------Browser Based App------->| Auth Code Grant with PKCE |
| +---------------------------+
|
| +---------------------------+
|>-------Native Mobile App------->| Auth Code Grant with PKCE |
+---------------------------+

Source