Search code examples
authenticationoauth-2.0nestjskeycloakoauth2resourceserver

Keycloak, Nestjs - ResourceGuard always results in 403 Forbidden Error?


I have a NestJS REST API. I try to use Keycloak as Authorization Services. I want to secure the endpoints of my REST API with resources, scopes and permissions.

The problem is, I get a 403 Forbidden Resource Error on every request. I try to explain my whole configuration with a lot of images. Am I missing something or have I misunderstood something?

Keycloak Configuration

Configuration of the client: config

My test rescource: image

My policy: image

My permission: image

Evaluation To test my configuration I use the internal evaluation tool. I have the user: "testcustomer" who is member of the group: Testproject. Therefore he should have access to the resource. The evaluation shows, it's working correctly: image

REST API:

In my NestJs REST API I'm using the nest-keycloak-connect-package.

This is the configuration of the KeycloakModule: image

My Test-Controller

image

My understanding of the package: When a user (in this case the testcustomer) sends a request to the API to the following URI: "http://localhost:3002/api/test/test", the resource from Keycloak is associated with it. And the testcustomer is authorized to call this endpoint. Other users who are not in the Testproject group will get a 403 Forbidden response.

The problem is that I always get a 403 error no matter if my user is in the group and it doesn't even matter if the resource exists in Keycloak at all.

Note: General authentication or even authorization via roles works.


Solution

  • thanks to the owner of the package I got the answer:

    https://github.com/ferrerojosh/nest-keycloak-connect/issues/137

    His answer/ solution:

    Ah I think its due to the fact your scopes have the : character in it.

    If you think of the file in the official keycloak-connect library: https://github.com/keycloak/keycloak-nodejs-connect/blob/f8e397cd7a1a763db5a45a07c3c3e40fec5cf8f2/middleware/enforcer.js#L18-L33

    It splits off permission which is permission:scope by simply a split :.

    What happened here is that the underyling keycloak-connect library receives a string of File:files:read and it gets sent to the keycloak enforcer as the resource File with the scope files.

    tldr; the solution is to remove the : character in your scope. If it doesn't work out for you, you can submit a ticket to the keycloak-connect team as I do not have control over this behavior.