我创建了一个自定义 Keycloak 端点(使用自定义领域资源提供程序工厂)。我可以使用 Postman 发布到此端点,并且它按预期工作。当我尝试从我的 SPA(Angular)应用程序发布到它时,我收到 CORS 错误。
我的 Web 源在我的 Keycloak 客户端配置中配置正确。但这些似乎不适用于我的自定义端点。
如何配置端点以允许跨源 POST?
我能够通过执行以下操作来配置自定义端点以支持 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();
}
Run Code Online (Sandbox Code Playgroud)
我不清楚是否有一种全球性的方法可以做到这一点。好像应该有。
在我的实际端点方法中,我必须使用 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();
}
Run Code Online (Sandbox Code Playgroud)
这里的响应允许所有来源。我不推荐这样做,但它让这段代码正常工作。可能可以绑定到 Keycloak 的客户端设置并返回“web origin”中设置的值。我还没有调查过这个。