Pac4j - CORS Allow Origin Not Matching Origin

103 views Asked by At

My javalin API receive a request on a route secured by pac4j. But no matter what I try, I always end up with a "CORS Allow Origin Not Matching Origin" error on OPTION, and "NS_ERROR_DOM_BAD_URI" on GET
Unprotected route works normally.

Here is my api :

val securityHandler: SecurityHandler = SecurityHandler(authenticationConfig, "KeycloakOidcClient")
app.before("/protected", securityHandler)
app.get("/protected") { ctx ->
  ctx.result("Hello Keycloak protected!")
}
app.get("/notprotected") { ctx ->
  ctx.result("Hello unprotected!")
}

And here is my config :

fun setUpAuthentication(properties: Properties): AuthenticationConfig {

  val oidcConfig: KeycloakOidcConfiguration = KeycloakOidcConfiguration()
  oidcConfig.setClientId(properties.get(KEYCLOAK_ID))
  oidcConfig.setSecret(properties.get(KEYCLOAK_SECRET))
  oidcConfig.setDiscoveryURI(properties.get(KEYCLOAK_DISC_URI))
  oidcConfig.setBaseUri(properties.get(KEYCLOAK_BASE_URI))
  oidcConfig.setRealm(properties.get(KEYCLOAK_REALM))
  oidcConfig.setClientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)

  val keyCloakClient = KeycloakOidcClient(oidcConfig)
  val clients = Clients(properties.get(API_BASE_URL)+"/callback", keyCloakClient)
  val config = AuthenticationConfig(clients)
  config.addAuthorizer("csfr", CsrfAuthorizer())
  return config
}

My keycloak client is configured with both the front-end and back-end url as allowed web origins (I even tried * or /* but it doesn't change anything)

What could be the cause ?

Edit :

I just tried to add a CorsMatcher as suggested but to no effect :

val corsMatcher = CorsMatcher()
corsMatcher.setAllowOrigin(null)
config.addMatcher("cors", corsMatcher)
return config

@jleleu is it what you had in mind in order to "a CORS configuration with the null host" ?

Edit 2 :

val keyCloakClient = KeycloakOidcClient(oidcConfig)
val clients = Clients(properties.get(API_BASE_URL)+"/callback", keyCloakClient)
val config = AuthenticationConfig(clients)
val corsMatcher = CorsMatcher()
corsMatcher.setAllowOrigin(properties.get(FRONT_URL) + " " + properties.get(KEYCLOAK_BASE_URI))
// also tried 
// corsMatcher.setAllowOrigin(properties.get(FRONT_URL))
// corsMatcher.setAllowOrigin(properties.get(KEYCLOAK_BASE_URI))
// but reading Matcher code it seems to overwrite the first one 
config.addMatcher("cors", corsMatcher)
return config
1

There are 1 answers

9
jleleu On

By default, security headers are applied by pac4j. Can you try using the SecurityHandler(authenticationConfig, "KeycloakOidcClient", "isAuthenticated", "none") constructor?