Code Monkey home page Code Monkey logo

nestjs-keycloak-admin's Introduction

Keycloak Admin Client for NestJs based on nestjs-keycloak-admin

Install using npm i --save @chongyejia/nestjs-keycloak-admin or yarn add @chongyejia/nestjs-keycloak-admin

Supported Keycloak version

  • 18.0.0

Initialize KeycloakModule

Then on your app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import KeycloakModule, { AuthGuard, ResourceGuard, RoleGuard } from '@chongyejia/nestjs-keycloak-admin'
import { APP_GUARD } from '@nestjs/core';

@Module({
  imports: [
    KeycloakModule.register({
      baseUrl: '',
      realmName: ''
      clientSecret: '',
      clientId: ''
    })
  ],
  controllers: [AppController],
  providers: [
    {
      provide: APP_GUARD,
      useClass: AuthGuard
    },
    {provide: APP_GUARD, useClass: ResourceGuard},
    {
      provide: APP_GUARD,
      useClass: RoleGuard,
    },
  ],
})
export class AppModule {}

Resource Management using User Managed Access (UMA)

By default @chongyejia/nestjs-keycloak-admin supports User Managed Access for managing your resources.

import { Controller, Get, Request, ExecutionContext, Post } from '@nestjs/common'
import {
  DefineResource,
  Public,
  KeycloakService,
  FetchResources,
  Resource,
  DefineScope,
  DefineResourceEnforcer,
  UMAResource,
  Scope,
} from '@chongyejia/nestjs-keycloak-admin'

@Controller('/organization')
@DefineResource('organization')
export class AppController {
  constructor(private readonly keycloak: KeycloakService) {}

  @Get('/hello')
  @Public()
  sayHello(): string {
    return 'life is short.'
  }

  @Get('/')
  @FetchResources()
  findAll(@Request() req: any): Resource[] {
    return req.resources as Resource[]
  }

  @Get('/:slug')
  @DefineScope('read')
  @EnforceResource({
    def: ({ params }) => params.slug,
    param: 'slug',
  })
  findBySlug(@Request() req: any): Resource {
    return req.resource as Resource
  }

  @Post('/')
  @DefineScope('create')
  async create(@Request() req: any): Promise<Resource> {
    let resource = new Resource({
      name: 'resource',
      displayName: 'My Resource',
    } as UMAResource)
      .setOwner(req.user._id)
      .setScopes([new Scope('organization:read'), new Scope('organization:write')])
      .setType('urn:resource-server:type:organization')
      .setUris(['/organization/123'])
      .setAttributes({
        valid: true,
        types: ['customer', 'any'],
      })

    resource = await this.keycloak.resourceManager.create(resource)

    // create organization on your resource server and add link to resource.id, to access it later.

    return resource
  }
}

Decorators

Here is the decorators you can use in your controllers.

Decorator Description
@User Retrieves the current Keycloak logged-in user. (must be per method, unless controller is request scoped.)
@AccessToken Retrieves the current access token. (must be per method, unless controller is request scoped.)
@DefineResource Define the keycloak application resource name.
@DefineScope Define the keycloak resource scope (ex: 'create', 'read', 'update', 'delete')
@EnforceResource
@FetchResources
@Public Allow any user to use the route.
@Roles Keycloak realm/application roles. Prefix any realm-level roles with "realm:" (i.e realm:admin)
  @Get('/hello')
  @Roles({roles: ['realm:admin'], mode: RoleMatchingMode.ANY})
  sayHello(@User() user: KeycloakUser, @AccessToken() accessToken): string {
    return `life is short. -${user.email}/${accessToken}`
  }

Contributors

Bugs and Contributions

If you find a bug, please report it using the issue tracker.

nestjs-keycloak-admin's People

Contributors

anonrig avatar semantic-release-bot avatar snyk-bot avatar dependabot[bot] avatar vincentdatrier avatar aktraore avatar xyezir avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.