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

keycloak-api-node

v1.1.0

Published

A Node.js package for Keycloak authentication and admin API integration with secure token encryption

Readme

Keycloak API Node

A NestJS-based package for Keycloak authentication and admin API integration.

Features

  • Token validation and role checking
  • Admin token generation
  • Keycloak admin API integration
  • Custom decorators for easy role checking
  • Secure token encryption and decryption

Installation

npm install keycloak-api-node

Configuration

You can initialize the KeycloakService with your configuration:

import { KeycloakService } from 'keycloak-api-node';

const keycloakService = new KeycloakService({
  clientId: "your-client-id",
  clientSecret: "your-client-secret",
  issuer: "https://your-keycloak-server/realms/your-realm",
  redirectUri: "http://localhost:3000/callback",
  // Optional encryption configuration
  encryptionKey: "your-32-character-encryption-key", // Must be 32 characters
  iv: "your-16-character-iv"                         // Must be 16 characters
});

Encryption Configuration

The service includes built-in AES-256-CBC encryption for enhanced security. You can configure it in two ways:

  1. Using Environment Variables (Recommended)

    KEYCLOAK_ENCRYPTION_KEY=your-32-character-encryption-key
    KEYCLOAK_IV=your-16-character-iv
  2. Direct Configuration

    const keycloakService = new KeycloakService({
      // ... other config
      encryptionKey: process.env.KEYCLOAK_ENCRYPTION_KEY,
      iv: process.env.KEYCLOAK_IV
    });

Important Security Notes:

  • The encryption key must be exactly 32 characters long
  • The initialization vector (IV) must be exactly 16 characters long
  • Never commit encryption keys or IVs to version control
  • Use environment variables in production
  • If not provided, default values will be used (not recommended for production)

For NestJS applications, you can provide the service in your module:

import { Module } from '@nestjs/common';
import { KeycloakService } from 'keycloak-api-node';

@Module({
  providers: [
    {
      provide: KeycloakService,
      useValue: new KeycloakService({
        clientId: process.env.KEYCLOAK_CLIENT_ID,
        clientSecret: process.env.KEYCLOAK_CLIENT_SECRET,
        issuer: process.env.KEYCLOAK_ISSUER,
        redirectUri: process.env.KEYCLOAK_REDIRECT_URI,
        encryptionKey: process.env.KEYCLOAK_ENCRYPTION_KEY,
        iv: process.env.KEYCLOAK_IV
      })
    }
  ],
  exports: [KeycloakService]
})
export class KeycloakModule {}

Usage

Module Setup

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { KeycloakModule } from 'keycloak-api-node';

@Module({
  imports: [
    ConfigModule.forRoot(),
    KeycloakModule
  ],
})
export class AppModule {}

Token Validation

You can use the @ValidateToken() decorator to automatically validate tokens in your controllers:

import { Controller, Get } from '@nestjs/common';
import { ValidateToken } from 'keycloak-api-node';

@Controller('users')
export class UserController {
  @Get('profile')
  async getProfile(@ValidateToken() token: string) {
    // token is already validated and decrypted
    return this.userService.getProfile(token);
  }
}

The ValidateToken decorator will:

  • Extract the token from the Authorization header
  • Validate the token's format
  • Decrypt the token if necessary
  • Check token expiration
  • Throw UnauthorizedException if validation fails

Important Notes About Token Encryption

The package uses a shared EncryptionStore to maintain consistent encryption settings across your application. This means:

  1. Encryption settings are shared application-wide
  2. The last configuration set will be used for all token validations
  3. If you're running multiple applications, they should use the same encryption settings

For production environments, always:

  1. Set custom encryption keys through environment variables
  2. Use different keys for different environments
  3. Never use the default development keys

Role-Based Access Control

Use the @KeycloakRole() decorator to protect routes:

@Get('admin/users')
@KeycloakRole('admin')
async getUsers(@ValidateToken() token: string) {
  return this.userService.getAllUsers(token);
}

Using the Decorator

import { Controller, Get } from '@nestjs/common';
import { KeycloakRole } from 'keycloak-api-node';

@Controller('api')
export class AppController {
  @Get('protected')
  async protectedEndpoint(@KeycloakRole('admin') tokenData: any) {
    return 'This endpoint is protected and requires admin role';
  }
}

Using the Service

import { Injectable } from '@nestjs/common';
import { KeycloakService } from 'keycloak-api-node';

@Injectable()
export class YourService {
  constructor(private readonly keycloakService: KeycloakService) {}

  async validateToken(token: string) {
    // Token will be automatically decrypted before validation
    return this.keycloakService.validateToken(token);
  }

  async checkRole(token: string, role: string) {
    // Token will be automatically decrypted before role check
    return this.keycloakService.checkUserRole(token, role);
  }
}

Security

This package implements several security measures:

  1. Token Encryption: All tokens are encrypted using AES-256-CBC encryption
  2. Automatic Token Validation: Includes expiration checking
  3. Role-based Access Control: Built-in role checking functionality
  4. Secure Configuration: Support for environment variables

License

MIT