Skip to content

Commit

Permalink
Add 'http.uri', 'user.agent' to enforcer claims, closes #123
Browse files Browse the repository at this point in the history
  • Loading branch information
ferrerojosh committed Oct 18, 2024
1 parent 5781008 commit f8b067b
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
4 changes: 3 additions & 1 deletion example/src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
Public,
Roles,
RoleMatchingMode,
RoleMatch,
} from 'nest-keycloak-connect';

@Controller()
Expand All @@ -27,7 +28,8 @@ export class AppController {
}

@Get('admin')
@Roles({ roles: ['admin'], mode: RoleMatchingMode.ALL })
@Roles('admin')
@RoleMatchingMode(RoleMatch.ANY)
adminRole() {
return 'Admin only!';
}
Expand Down
2 changes: 1 addition & 1 deletion example/src/product/product/product.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class ProductController {
}

@Get(':code')
@Roles({ roles: ['realm:basic', 'realm:admin'] })
@Roles('realm:basic', 'realm:admin')
findByCode(@Param('code') code: string) {
return this.service.findByCode(code);
}
Expand Down
18 changes: 17 additions & 1 deletion src/guards/resource.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,22 @@ export class ResourceGuard implements CanActivate {
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const defaultEnforcerOpts: KeycloakConnect.EnforcerOptions = {
claims: (request: any) => {
const httpUri = request.url;
const userAgent = request.headers['user-agent'];

this.logger.verbose(
`Enforcing claims, http.uri: ${httpUri}, user.agent: ${userAgent}`,
);

return {
'http.uri': [httpUri],
'user.agent': userAgent,
};
},
};

const resource = this.reflector.get<string>(
META_RESOURCE,
context.getClass(),
Expand All @@ -64,7 +80,7 @@ export class ResourceGuard implements CanActivate {
this.reflector.getAllAndOverride<KeycloakConnect.EnforcerOptions>(
META_ENFORCER_OPTIONS,
[context.getClass(), context.getHandler()],
);
) ?? defaultEnforcerOpts;

// Default to permissive
const policyEnforcementMode =
Expand Down

0 comments on commit f8b067b

Please sign in to comment.