CORS problem in custom REST endpoint

Hello,

For the needs of our project, we’ve created a plugin to implement a custom REST endpoint by using the following documentation: Server Developer Guide.

By calling this endpoint via a front application, we have a CORS problem: “has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

However, by using a REST Postman client, we don’t have that problem.

To resolve this issue, we’ve tried to manually add the “Access-Control-Allow-Origin” header in the response using following technics:

  1. return Response.ok().entity(data).header(“Access-Control-Allow-Origin”, “*”).build();

  2. return Cors.add(request, Response.ok().entity(data))
    .preflight()
    .allowAllOrigins()
    .allowedMethods(“GET”, “PUT”, “POST”, “DELETE”)
    .auth()
    .build();

  3. return Response
    .status(200)
    .header(“Access-Control-Allow-Origin”, “*”)
    .header(“Access-Control-Allow-Headers”, “origin, content-type, accept, authorization”)
    .header(“Access-Control-Allow-Methods”, “GET, POST, PUT, DELETE, OPTIONS, HEAD”)
    .entity(data)
    .build();

By using a REST Postman client, we’ve observed that some of those technics have allowed us to add the needed header in the response, but the front application still wasn’t working.

To test the theory that we cannot allow all origins, we’ve tried to limit them to the precise ones, which also haven’t given any results.

Adding ‘cors: true’ or ‘“enable-cors”: true’ in keycloak.json of the front application also hasn’t solved this issue.

Could you advise us on the solution to this problem, please?

See spec: Access-Control-Allow-Headers - HTTP | MDN

In requests with credentials, it is treated as the literal header name " * " without special semantics. Note that the Authorization header can’t be wildcarded and always needs to be listed explicitly.

So are you allowing all origins with wild char or just one origin with literal name *? I guess second option is right.

We’ve tried to use localhost origin instead of *, but it hasn’t worked either.

Doc is your good friend for development: Origin - HTTP | MDN

Origin: <scheme> “://” <hostname> [ “:” <port> ]

localhost is definitely not a valid origin. Also some browsers (google: chrome cors issue localhost) may ignore it for localhost origin.

I haven’t used directly localhost, I used it as http://localhost:3000. But it doesn’t work. I’ve tried other browsers. It doesn’t work either.

Hi, i’m facing the same problem here. Have you found a way to configure CORS on a Keycloak custom rest endpoint?

Hi, I’m using keycloak 9.0.2. I’ve tried adding endpoint api as well as adding custom module as described in the keycloak provider examples; when reaching the apis with authentication, both give the same as described above: CORS preflight didn’t succeed. Any luck in thinking this problem through?
Thanks