自定义Keycloak端点的CORS

时间:2019-07-02 23:47:53

标签: cors keycloak

我已经创建了一个自定义Keycloak端点(使用自定义领域资源提供程序工厂)。我可以使用Postman发布到此端点,并且可以按预期工作。当我尝试从SPA(Angular)应用程序发布到它时,出现CORS错误。

我的Web起源在Keycloak客户端配置中正确配置。但是这些似乎不适用于我的自定义端点。

如何配置我的端点以允许跨源POST?

1 个答案:

答案 0 :(得分:1)

通过执行以下操作,我可以配置自定义端点以支持CORS:

添加了预检jax-rs端点方法。这允许浏览器发出预检OPTIONS请求,并接收有关允许使用哪些标头,方法,源等的信息:

@OPTIONS
@Path("users")
public Response handleCorsPreflight(@Context final HttpRequest request) {
    logger.info("Received CORS preflight request for ext/user; request is " + request);
    return Cors.add(request, Response.ok())
            .preflight()
            .allowAllOrigins()
            .allowedMethods("GET", "PUT", "POST", "DELETE")
            .exposedHeaders("Location")
            .auth()
            .build();
}

我尚不清楚是否存在全球性的方法。似乎应该有。

在我的实际端点方法中,我不得不使用Keycloak的静态Cors.add方法处理响应。例如:

@POST
@Path("foo")
@Consumes(MediaType.APPLICATION_JSON)
public Response createFoo(final FooRepresentation rep,
                                                   @Context final HttpRequest request,
                                                   @Context final HttpHeaders headers) {
Response response = createFoo(rep);
return Cors.add(request, Response.fromResponse(response))
            .allowAllOrigins()
            .allowedMethods("GET", "PUT", "POST", "DELETE")
            .exposedHeaders("Location")
            .auth()
            .build();

}

此处的响应允许所有来源。我不建议这样做,但是它使此代码起作用。可能可以绑定Keycloak的客户端设置并返回在“ web origin”中设置的值。我还没有对此进行调查。