Keycloak 自定义 REST 端点中的 CORS 错误

CORS error in Keycloak custom REST endpoint

所以我在这里阅读了关于如何扩展服务器的文档:

https://wjw465150.gitbooks.io/keycloak-documentation/content/server_development/topics/extensions.html

并遵循本教程:

https://dev.to/silentrobi/keycloak-custom-rest-api-search-by-user-attribute-keycloak-3a8c

我正在尝试通过自定义属性获取用户,到目前为止,当我尝试使用 Postman 时,它可以正常工作。但是,当我尝试从我的 angular 应用程序发送 get 请求时,它返回了 CORS 错误:请求的资源上不存在 'Access-Control-Allow-Origin' header。我尝试添加以 localhost 作为原点的 @CrossOrigin 注释,但它没有用。我还尝试在以 * 或本地主机为原点的响应中手动设置 headers,如下所示:


    @GET
    @Path("users/search_by_attribute")
    @NoCache
    @Produces({ MediaType.APPLICATION_JSON })
    @Encoded
    public Response searchUsersByAttribute(@DefaultValue(searchBy) @QueryParam("attribute") String attribute, @QueryParam("value") String value) {
                List<UserDto> list = session.users().searchForUserByUserAttribute(attribute, value, session.getContext().getRealm()).stream().map(e -> userMapper.mapToUserDto(e)).collect(Collectors.toList());
                return Response.status(200)
                .header("Access-Control-Expose-Headers", "*")
                .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(list)
                .build();
    }

但是也没用。有没有办法在端点或服务器上配置 CORS?

您需要响应@solveMe 提到的预检选项请求。

@OPTIONS
@Path("{any:.*}")
public Response preflight() {
    HttpRequest request = session.getContext().getContextObject(HttpRequest.class);
    return Cors.add(request, Response.ok()).auth().preflight().build();
}

会话是KeycloakSession。 Cors class 在 org.keycloak.services.resources

这里有一个 Repo 可以帮助你,它是一个 Keycloak 自定义端点,可以通过自定义属性获取用户,我在我的 Angular 应用程序中使用它,处理 Cors 错误并实现身份验证.