
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
@programow/nest-keycloak
Advanced tools
A couple observations since this is not super well documented:
Enforce resource def function will receive as parameter the request when working with rest apis or the GqlExecutionContext when on GraphQL. When param is specified on that decorator, that we will try to find a resource with keycloak where 'param' = def(request) or 'param' = def(gqlcontext)
As per my tests, params doesn't seem reliable and could result in authorizing routes that shouldn't so we will avoid using it.
Fetch Resources will fetch absolutely all resources the user has access to on keycloak and attatch it to request.resources
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 {}
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
}
}
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}`
}
Role guard must be used with auth guard Role guard also works for clients and client roles Resource/scope guards also work with clients and their credentials. e.g. if there's some policy that only requesters with client role x are allowed.
For resource guard, scope must be specified otherwise it will be infered through the request method
To develop: Set path to the root of this repository on the dependencies of other module
FAQs
Keycloak Admin Provider for Nest.js
The npm package @programow/nest-keycloak receives a total of 2 weekly downloads. As such, @programow/nest-keycloak popularity was classified as not popular.
We found that @programow/nest-keycloak demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.