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

nestjs-keycloak-auth-muvstok

v1.0.0

Published

A library for SSO Keycloak integration

Readme

Auth Keycloak Library for NestJS

Uma biblioteca simples para integração com Keycloak em aplicações NestJS.

Características

  • Autenticação via JWT tokens do Keycloak
  • Guard global para proteção automática de endpoints
  • Suporte a endpoints públicos via decorator @Public()
  • Validação de tokens emitidos por outras aplicações do mesmo realm
  • Implementação simples e direta sem dependências complexas

Instalação

npm install nestjs-keycloak-auth-muvstok

Configuração

  1. Configure o módulo em seu app.module.ts:
import { Module } from '@nestjs/common';
import { AuthModule } from 'nestjs-keycloak-auth-muvstok';

@Module({
  imports: [
    AuthModule.register({
      config: {
        realm: 'seu-realm',
        authServerUrl: 'http://seu-keycloak/auth',
        clientId: 'seu-client-id',
        clientSecret: 'seu-client-secret',
      },
    }),
  ],
})
export class AppModule {}
  1. Use o decorator @Public() para endpoints públicos:
import { Controller, Get } from '@nestjs/common';
import { Public } from 'nestjs-keycloak-auth-muvstok';

@Controller('api')
export class AppController {
  @Public()
  @Get('public')
  getPublic() {
    return 'Este endpoint é público';
  }

  @Get('protected')
  getProtected() {
    return 'Este endpoint requer autenticação';
  }
}

Acesso ao Usuário Autenticado

O objeto do usuário autenticado estará disponível na requisição:

import { Controller, Get, Request } from '@nestjs/common';

@Controller('api')
export class AppController {
  @Get('me')
  getMe(@Request() req) {
    return req.user; // { id, username, email, roles, resourceAccess, clientId }
  }
}

Notas de Segurança

  • A biblioteca valida automaticamente o issuer (realm) e audience (clientId) dos tokens
  • Tokens expirados são automaticamente rejeitados
  • Tokens de outras aplicações do mesmo realm são aceitos desde que válidos

Configuração Assíncrona

Se você precisar carregar as configurações de forma assíncrona (por exemplo, usando o ConfigService do NestJS):

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthModule } from 'nestjs-keycloak-auth-muvstok';

@Module({
  imports: [
    ConfigModule.forRoot(),
    AuthModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        config: {
          realm: configService.get('KEYCLOAK_REALM'),
          authServerUrl: configService.get('KEYCLOAK_AUTH_SERVER_URL'),
          clientId: configService.get('KEYCLOAK_CLIENT_ID'),
          clientSecret: configService.get('KEYCLOAK_CLIENT_SECRET'),
        },
      }),
    }),
  ],
})
export class AppModule {}

  ]
})
export class AppModule {}

Protecting Routes

Você tem duas opções para proteger suas rotas:

1. Usando Guards Globais (Recomendado)

Ao habilitar os guards globais na configuração do módulo (passando true como segundo parâmetro), todas as rotas serão protegidas por padrão. Use o decorator @Public() para marcar rotas públicas:

import { Roles, Public } from 'nestjs-keycloak-auth-muvstok';

@Controller('users')
export class UsersController {
  @Get()
  @Roles('admin') // Rota protegida que requer role 'admin'
  findAll() {
    return this.usersService.findAll();
  }

  @Get('public')
  @Public() // Rota pública, não requer autenticação
  publicRoute() {
    return 'This is a public route';
  }
}

2. Usando Guards por Controller/Rota

Se você preferir um controle mais granular, pode aplicar os guards manualmente:

import { KeycloakAuthGuard, RolesGuard, Roles } from 'nestjs-keycloak-auth-muvstok';

@Controller('users')
@UseGuards(KeycloakAuthGuard, RolesGuard)
export class UsersController {
  @Get()
  @Roles('admin')
  findAll() {
    return this.usersService.findAll();
  }
}

### Environment Variables

```env
KEYCLOAK_REALM=your-realm
KEYCLOAK_AUTH_SERVER_URL=https://your-keycloak-server/auth
KEYCLOAK_CLIENT_ID=your-client-id
KEYCLOAK_SECRET=your-client-secret
KEYCLOAK_PUBLIC_KEY=your-public-key
KEYCLOAK_SSL_REQUIRED=external
KEYCLOAK_CONFIDENTIAL_PORT=0

API Reference

Decorators

  • @Roles(...roles: string[]) - Specify required roles for a route
  • @Public() - Mark a route as public (no authentication required)

Guards

  • KeycloakAuthGuard - Validates JWT tokens
  • RolesGuard - Validates user roles

Services

  • KeycloakService - Provides methods for token validation, refresh, and session management
    • validateToken(token: string) - Validates a JWT token
    • refreshToken(refreshToken: string) - Refreshes an expired token
    • logout(sessionId: string) - Invalidates a user session

You can customize these settings by extending the KeycloakService class.