What is the proper way to register policy-enforcer configuration in ktor

523 views Asked by At

In spring boot, adding keycloak adaptor and "keycloak.policy-enforcer-config.claimInformationPointConfig.claims[claim-from-uri]={ request.uri }" to application.properties file, I am able to receive "claim-from-uri" in keycloak javascript policy. But using similar settings in ktor does not work.

I have added "policy-enforcer" to keyclaok.json but "claim-from-uri" property is always null in javascript policy in keycloak.

// js policy in keycloak
var context = $evaluation.getContext();
var attributes = context.getAttributes();
var realm = $evaluation.getRealm();
var httpUri = attributes.getValue('http.uri');
var claimFromUri = attributes.getValue('claim-from-uri');

My usecase is to get the claim from the URI and then use it to get the policy from the keycloak server.

Below is my keycloak.json file.

{
  "realm": "test-realm",
  "auth-server-url": "https://localhost:8080/auth",
  "ssl-required": "none",
  "resource": "api-resource",
  "public-client": true,
  "policy-enforcer": {
    "enforcement-mode": "ENFORCING",
    "paths": [
      {
        "path": "/api/*",
        "claim-information-point": {
          "claims": {
            "claim-from-uri": "{request.uri}"
          }
        },
        "methods": [
          {
            "method": "GET",
            "scopes": ["get", "GET"]
          },
          {
            "method": "POST",
            "scopes": ["post", "POST"]
          }
        ]
      }
    ]
  }
}


val keycloakProvider = OAuthServerSettings.OAuth2ServerSettings(
    name = "keycloak",
    authorizeUrl = "https://localhost:8082/auth/realms/test-realm/protocol/openid-connect/auth",
    accessTokenUrl = "https://localhost:8082/auth/realms/test-realm/protocol/openid-connect/token",
    clientId = "test-realm-backend",
    clientSecret = "client-secret",
    accessTokenRequiresBasicAuth = false,
    requestMethod = HttpMethod.Post,
    )

//application setup
    install(Authentication) {
            oauth("keycloak") {
                client = HttpClient(Apache)
                providerLookup = { keycloakProvider }
                urlProvider = { "http://localhost:8080/callback" }
            }
        }

// routing
      authenticate("keycloak") {
        get("/api/{name}") {
          val principal: OAuthAccessTokenResponse.OAuth2? = call.authentication.principal()
          call.sessions.set(UserSession("Bearer $principal?.accessToken.toString()"))
          val name = call.parameters["name"] ?: "name missing in parameter"
          val user = User(name)
          call.respond(user)

      }
  }
0

There are 0 answers