Coder Social home page Coder Social logo

anonrig / nestjs-keycloak-admin Goto Github PK

View Code? Open in Web Editor NEW
176.0 2.0 24.0 2.24 MB

Keycloak client and admin provider for Nest.js applications with built-in User Managed Access (UMA) and ACL support.

Home Page: https://npmjs.com/package/nestjs-keycloak-admin

License: MIT License

TypeScript 98.08% JavaScript 1.92%
keycloak nodejs javascript nestjs typescript nest

nestjs-keycloak-admin's Introduction

Keycloak for Nest.js

Installation

Install using npm i --save nestjs-keycloak-admin or pnpm add nestjs-keycloak-admin

ESM restriction

  • Due to @keycloak/keycloak-admin-client package, nestjs-keycloak-admin can't support CommonJS at the moment. The team behind keycloak-admin-client made the decision to have a breaking change and support CommonJS. Please refer to this Github issue for more information about their decision-making process.
  • You need to switch to ESM to run this package without any issues. Please refer to this Github gist for more information.

Initialize KeycloakModule

Then on your app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import KeycloakModule, { AuthGuard, ResourceGuard, RoleGuard } from '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 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 '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

@Get('/hello')
@Roles({roles: ['realm:admin'], mode: RoleMatchingMode.ANY})
sayHello(@User() user: KeycloakUser, @AccessToken() accessToken): string {
  return `life is short. -${user.email}/${accessToken}`
}

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)

nestjs-keycloak-admin's People

Contributors

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

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

nestjs-keycloak-admin's Issues

Way to disable Token ISS Validation

Is there a way to disable the ISS validation of the token? This is possible with typical Keycloak Libraries for .NET and required for some setups (especially in development)!

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Getting 404 on startup

Hi,

I just tried to replace the nest-keycloak-connect library with your one. Unfortunately with the same settings i'm getting an error on startup with very limited information.

I tried to reproduce the issue with the example backend there seems to be some issues with it.

In the following screenshots you can see all logs I'm getting:
CleanShot 2022-07-19 at 14 17 58

I'm happy to provide more information if nessessary.

Invalid grant

Hello, I hope that you are well.

I have an issue occuring when I use the Admin client services. Keycloak returns invalid_credentials, I believe that's happening because the grant is expired and the refreshGrant method isn't working.

I use the Admin client services to authenticate my users and return their tokens, create new users, update existing users...

Could you help me?

Cannot use import statement outside a module import { KeycloakModule } from './module'

im having SyntaxError: Cannot use import statement outside a module import { KeycloakModule } from './module'; even after adding "type": "module" in my package.json

using the "nestjs-keycloak-admin": "^2.0.0" version

here is my tsconfig

{
  "compilerOptions": {
    "module": "node16",
    "declaration": true,
    "removeComments": true,
    "noEmitOnError": true,
    "moduleDetection": "force",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "ES2020",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "resolveJsonModule": false,
    "moduleResolution": "node16",
    "skipLibCheck": true,
    "strict": true,
    "strictNullChecks": true,
    "strictPropertyInitialization": false,
    "noImplicitAny": true,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false,
    "useUnknownInCatchVariables": true,
    "esModuleInterop": true,
    "allowJs": true,
    "paths": {
      "@application/*":["./src/application/*"],
      "@helpers/*":["./src/helpers/*"],
      "@infra/*":["./src/infra/*"],
      "@test/*":["./test/*"]
    },
  },
}

Role Guard

I would like to know what is the annotation for Roles like we have in nest-keycloak-connect.
Ex:
@ Roles({ roles: ['admin'], mode: RoleMatchingMode.ANY })

Error: change require() to a dynamic import()

Hi

After installing this package and starting my nestjs project I get the following error:

/source/node_modules/nestjs-keycloak-admin/dist/main/service.js:18
const keycloak_admin_client_1 = __importDefault(require("@keycloak/keycloak-admin-client"));
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /source/node_modules/@keycloak/keycloak-admin-client/lib/index.js from /source/node_modules/nestjs-keycloak-admin/dist/main/service.js not supported.
Instead change the require of index.js in /source/node_modules/nestjs-keycloak-admin/dist/main/service.js to a dynamic import() which is available in all CommonJS modules.
at Object. (/source/node_modules/nestjs-keycloak-admin/dist/main/service.js:18:49)
at Object. (/source/node_modules/nestjs-keycloak-admin/dist/main/module.js:13:19)
at Object. (/source/node_modules/nestjs-keycloak-admin/dist/main/index.js:17:18)
at Object. (/source/dist/common/auth/auth.module.js:12:33)
at Object. (/source/dist/app.module.js:11:23)
at Object. (/source/dist/main.js:8:22)

I use Node v17.8.0, "nestjs-keycloak-admin": "1.8.8"

keycloak-admin dependency deprecated

Hi,
thank you for this great package, I started out with keycloak recently and your nestjs integration is really what I was looking for!

During my research on which packages to use I stumbled upon @keycloak/keycloak-admin-client and then I saw you are using the previous version keycloak-admin which seems to be deprecated and moved to @keycloak/keycloak-admin-client.

I think @keycloak/keycloak-admin-client should be used as dependency in your module.

Thanks!

ERR_REQUIRE_ESM

Error [ERR_REQUIRE_ESM]: require() of ES Module ./node_modules/@keycloak/keycloak-admin-client/lib/index.js from ./node_modules/nestjs-keycloak-admin/dist/main/service.js not supported.
Instead change the require of index.js in ./node_modules/nestjs-keycloak-admin/dist/main/service.js to a dynamic import() which is available in all CommonJS modules.

platform: mac os
node version: v16.17.0
nestjs version: 9.0
nestjs-keycloak-admin version: 1.8.7
keycloak version: 19.0.1
keycloak docker image: quay.io/keycloak/keycloak:19.0.1

ESM restriction - what to do?

You stated

Due to @keycloak/keycloak-admin-client package, nestjs-keycloak-admin can't support CommonJS at the moment. The team behind keycloak-admin-client made the decision to have a breaking change and support CommonJS. Please refer to this Github issue for more information about their decision-making process.

What do I need to change in my nestjs configuration for it to work?

Error: Cannot find module 'graphql'

We get the following error when trying to start our application after installing the nestjs-keycloak-admin package:

Full Error

Error: Cannot find module 'graphql'
- root/node_modules/@nestjs/graphql/dist/decorators/directive.decorator.js
- root/node_modules/@nestjs/graphql/dist/decorators/index.js
- root/node_modules/@nestjs/graphql/dist/index.js
- root/node_modules/nestjs-keycloak-admin/dist/main/utils/extract-request.js
- root/node_modules/nestjs-keycloak-admin/dist/main/guards/auth.guard.js
- root/node_modules/nestjs-keycloak-admin/dist/main/index.js
- root/dist/common/auth/auth.module.js
- root/dist/app.module.js
- root/dist/main.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (root/node_modules/@nestjs/graphql/dist/decorators/directive.decorator.js:4:19)
    at Module._compile (node:internal/modules/cjs/loader:1099:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:999:19)

We can't use nestjs-keycloak-admin without installing graphql, even though we don't use graphql. It runs after installing graphql manually as a dependency in our project.

Is there any way to use this package without installing graphql manually?

How to Refresh Token automatically

Hey guys,

I'm using this module in a project, it was already for production, but I found a problem that I can't solve. I use the keycloakService to create a new user in the keycloak through my API and I use the keycloak guard in APP_GUARD.

The API works as expected for a while, until Keycloak issues 401 to the system whenever someone makes a request, I believe that the request dies in the Guard, because the moment the token is extracted from the request and the system will check in the Keycloak if the token is valid, the Keycloak invalidates the API token (not that of the request) and does not allow validating the request token, returning an AXIOS 401 error, my global error handle captures, inserts the error message that came on AXIOS in response and issues status 500.

I am currently increasing the lifetime of my API client token. However I believe that there is another solution in which the API updates using the refresh token automatically so as not to disconnect from the Keycloak.

Note: I have not found this solution over the internet.

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.