Reactjs – Keycloak CORS issue associated with login redirect

corskeycloakreactjsspring-boot

Similar questions here and here have not helped me resolve the problem.

I am using Keycloak 4.4.0 to secure my REST service, which is implemented using Spring Boot and I am using React for the front end.

I get a CORS error when the front end (running on localhost:3000) makes an API call to localhost:8080/login and is redirected to the Keycloak login page.

The error is:

localhost/:1 Failed to load http://localhost:8080/login: Redirect from 'http://localhost:8080/login' to 'http://localhost:9080/auth/realms/hbs/protocol/openid-connect/auth?response_type=code&client_id=hbs&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Flogin&state=ab5034a9-4baa-4be3-9ec1-feefbe5f9c0b&login=true&scope=openid' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

I have added a single value of '*' to the Web Origins config section in the Keycloak client.

I have annotated my REST controller as follows:

@RestController
class MyController
{
    @CrossOrigin
    @GetMapping("/login")
    public ResponseEntity<Foo> getFoo(Principal principal)
    {
        return ResponseEntity.ok(new Foo("blah"));
    }
}

I have enabled Keycloak and CORS in the application properties:

keycloak.cors = true
keycloak.enabled = true

If I disable Keycloak and CORS, problem goes away.

As described here, I suspect the issue is to do with the Keycloak server not responding with any Access-Control-Allow-Origin headers despite Web Origins being correctly configured in the Keycloak admin portal. But I'm not completely sure how to confirm this.

Best Answer

Imagine the following json below is your Keycloak configuration:

{
  "realm" : "cors",
  "resource" : "cors-database-service",
  "auth-server-url": "http://localhost-auth:8080/auth",
  "bearer-only" : true,
  "ssl-required": "external",
  "enable-cors": true
}

Try adding the last line to your configuration file. Let me know if it worked for you!

OBS: I'm facing the same issue, but I'm using Wildfly/JBOSS adapters and making this configuration inside the application server.

@EDIT: This worked fine for me.

Try changing the "Access Type" to bearer-only inside your REST Client on Keycloak.

Also, don't forget to add the parameter {"{"Authorization" : "bearer " + $TOKEN} when sending HTTP requests from your client to your RESTful API.