npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@sftech/nestjs-auth-backend

v1.0.0

Published

A standalone, reusable NestJS library for OAuth 2.0 / OIDC authentication with Authorization Code Flow.

Readme

@sftech/nestjs-auth-backend

A standalone, reusable NestJS library for OAuth 2.0 / OIDC authentication with Authorization Code Flow.

This library provides a complete authentication microservice that can be used as a central auth service for your microservices architecture.

Features

  • OAuth 2.0 / OIDC Authorization Code Flow with PKCE support
  • Database-backed session management using TypeORM
  • Session-based authentication with HTTP-only cookies
  • Token management (Access Token, Refresh Token, ID Token)
  • Single Sign-On (SSO) with provider logout support
  • Clean Architecture (domain, application, infrastructure, presentation)
  • REST API endpoints for authentication flows

Installation

npm install @sftech/nestjs-auth-backend

Peer Dependencies

npm install @sftech/nestjs-core @sftech/nestjs-db

Usage

1. Configure Module

import { Module } from '@nestjs/common';
import { NestjsAuthBackendModule } from '@sftech/nestjs-auth-backend';

@Module({
  imports: [
    NestjsAuthBackendModule.register({
      // Module configuration options
    }),
  ],
})
export class AppModule {}

2. Configuration

The module uses configuration values from @sftech/nestjs-core configuration system. Add the following to your app.config.json:

{
  "OAUTH_PROVIDER_URL": "https://your-oauth-provider.com/realms/your-realm",
  "OAUTH_AUTHORIZATION_ENDPOINT": "https://your-oauth-provider.com/realms/your-realm/protocol/openid-connect/auth",
  "OAUTH_TOKEN_ENDPOINT": "https://your-oauth-provider.com/realms/your-realm/protocol/openid-connect/token",
  "OAUTH_USERINFO_ENDPOINT": "https://your-oauth-provider.com/realms/your-realm/protocol/openid-connect/userinfo",
  "OAUTH_END_SESSION_ENDPOINT": "https://your-oauth-provider.com/realms/your-realm/protocol/openid-connect/logout",
  "OAUTH_CLIENT_ID": "your-client-id",
  "OAUTH_CLIENT_SECRET": "your-client-secret",
  "OAUTH_REDIRECT_URL": "http://localhost:3000/api/auth/callback",
  "OAUTH_FRONTEND_CALLBACK_URL": "http://localhost:4200/auth/callback",
  "OAUTH_SCOPE": "openid profile email roles",
  "OAUTH_SESSION_MODE": "single",
  "OAUTH_SESSION_MAX_AGE": "3600000"
}

Configuration Parameters

| Parameter | Required | Description | Example | |-----------|----------|-------------|---------| | OAUTH_PROVIDER_URL | Yes | Base URL of OAuth provider | https://keycloak.example.com/realms/myrealm | | OAUTH_AUTHORIZATION_ENDPOINT | Yes | OAuth authorization endpoint | https://keycloak.example.com/realms/myrealm/protocol/openid-connect/auth | | OAUTH_TOKEN_ENDPOINT | Yes | OAuth token endpoint | https://keycloak.example.com/realms/myrealm/protocol/openid-connect/token | | OAUTH_USERINFO_ENDPOINT | Yes | OAuth userinfo endpoint | https://keycloak.example.com/realms/myrealm/protocol/openid-connect/userinfo | | OAUTH_END_SESSION_ENDPOINT | No | OAuth logout endpoint (for SSO logout) | https://keycloak.example.com/realms/myrealm/protocol/openid-connect/logout | | OAUTH_CLIENT_ID | Yes | OAuth client ID | my-app | | OAUTH_CLIENT_SECRET | Yes | OAuth client secret | your-secret-here | | OAUTH_REDIRECT_URL | Yes | OAuth callback URL (this service) | http://localhost:3000/api/auth/callback | | OAUTH_FRONTEND_CALLBACK_URL | No | Frontend callback URL (after login) | http://localhost:4200/auth/callback | | OAUTH_SCOPE | Yes | OAuth scopes to request | openid profile email roles | | OAUTH_SESSION_MODE | No | Session mode: single or multi | single (default) | | OAUTH_SESSION_MAX_AGE | No | Session max age in milliseconds | 3600000 (1 hour, default) |

Note: Session cookie name is fixed to oauth_session (not configurable).

3. Keycloak Example

For Keycloak, the endpoints follow this pattern:

{
  "OAUTH_PROVIDER_URL": "https://your-keycloak.com/realms/your-realm",
  "OAUTH_AUTHORIZATION_ENDPOINT": "https://your-keycloak.com/realms/your-realm/protocol/openid-connect/auth",
  "OAUTH_TOKEN_ENDPOINT": "https://your-keycloak.com/realms/your-realm/protocol/openid-connect/token",
  "OAUTH_USERINFO_ENDPOINT": "https://your-keycloak.com/realms/your-realm/protocol/openid-connect/userinfo",
  "OAUTH_END_SESSION_ENDPOINT": "https://your-keycloak.com/realms/your-realm/protocol/openid-connect/logout"
}

REST API Endpoints

The module provides the following REST endpoints under /api/auth:

GET /auth/login

Initiates OAuth login flow by redirecting to OAuth provider.

Query Parameters:

  • redirect_url (optional): URL to redirect to after successful login

Response: 302 Redirect to OAuth provider


GET /auth/callback

Handles OAuth callback after user authentication. Exchanges authorization code for tokens and creates session.

Query Parameters:

  • code (required): Authorization code from OAuth provider
  • state (required): State parameter for CSRF validation

Response: 302 Redirect to frontend callback URL with session cookie


GET /auth/status

Returns current authentication status. Does not require authentication.

Response:

{
  "authenticated": true,
  "userId": "user-id",
  "email": "[email protected]",
  "name": "John Doe",
  "roles": ["admin", "user"],
  "expiresAt": "2024-12-31T23:59:59.000Z",
  "timeRemaining": 3600000
}

GET /auth/user

Returns current user information from session. Requires authentication.

Response:

{
  "sub": "user-id",
  "email": "[email protected]",
  "name": "John Doe",
  "roles": ["admin", "user"],
  "expiresAt": "2024-12-31T23:59:59.000Z",
  "timeRemaining": 3600000
}

POST /auth/refresh

Refreshes access token using refresh token. Extends session lifetime. Requires authentication.

Response:

{
  "message": "Tokens refreshed successfully",
  "expiresAt": "2024-12-31T23:59:59.000Z",
  "timeRemaining": 3600000
}

POST /auth/logout

Ends user session by deleting from database and clearing cookie. If OAUTH_END_SESSION_ENDPOINT is configured, redirects to OAuth provider logout for SSO logout.

Response (without provider logout):

{
  "message": "Logout successful"
}

Response (with provider logout): 302 Redirect to OAuth provider logout endpoint


GET /auth/logout/callback

Handles OAuth provider logout callback. After the OAuth provider completes logout, they redirect back to this endpoint, which then redirects to the frontend.

Response: 302 Redirect to frontend callback URL

Authentication Flow

Login Flow

  1. Frontend calls GET /auth/login
  2. Backend generates PKCE challenge and redirects to OAuth provider
  3. User authenticates at OAuth provider
  4. OAuth provider redirects back to GET /auth/callback?code=xxx&state=xxx
  5. Backend exchanges code for tokens (with PKCE verifier)
  6. Backend creates session in database
  7. Backend sets oauth_session cookie (HTTP-only, Secure, SameSite)
  8. Backend redirects to frontend callback URL
  9. Frontend stores cookie and is now authenticated

Logout Flow

  1. Frontend calls POST /auth/logout
  2. Backend deletes session from database
  3. Backend clears oauth_session cookie
  4. If OAUTH_END_SESSION_ENDPOINT configured:
    • Backend redirects to OAuth provider logout with id_token_hint
    • OAuth provider clears SSO session
    • OAuth provider redirects back to GET /auth/logout/callback (backend)
    • Backend redirects to OAUTH_FRONTEND_CALLBACK_URL (frontend)
  5. Otherwise: Returns JSON success response

Session Validation

Other microservices can validate sessions by calling GET /auth/status with the session cookie.

See @sftech/nestjs-auth for client library to validate sessions from microservices.

Session Management

Sessions are stored in the database using TypeORM. The session entity includes:

  • sessionId: Unique session identifier (stored in cookie)
  • userId: User ID from OAuth provider
  • accessToken: OAuth access token
  • refreshToken: OAuth refresh token (optional)
  • idToken: OIDC ID token (used for provider logout)
  • expiresAt: Session expiration timestamp
  • userInfo: Cached user information (email, name, roles)

Session Modes

  • Single mode (OAUTH_SESSION_MODE=single): Only one active session per user. New login invalidates previous session.
  • Multi mode (OAUTH_SESSION_MODE=multi): Multiple concurrent sessions allowed per user.

Architecture

This library follows Clean Architecture principles:

lib/
├── domain/                 # Core business models and interfaces
│   ├── models/            # Session, UserInfo domain models
│   ├── repositories/      # Repository interfaces (ports)
│   └── oauth-options.interface.ts
├── application/           # Use cases and business logic
│   └── usecases/          # Login, Callback, Logout, Refresh, etc.
├── infrastructure/        # External concerns
│   ├── entities/         # TypeORM database entities
│   ├── repositories/     # Repository implementations
│   └── mappers/          # Domain ↔ Entity mapping
└── presentation/          # REST API layer
    ├── controllers/      # AuthController
    ├── dtos/            # Request/Response DTOs
    └── guards/          # SessionGuard

Building

nx build nestjs-auth-backend

Publishing

# Build first
nx build nestjs-auth-backend

# Navigate to dist folder
cd dist/libs/nestjs-auth-backend

# Publish to npm
npm publish --access public

License

MIT