使用Keycloak时静默认证CORS问题

Silent authentication CORS problem when using Keycloak

我正在尝试使用以下调用在我的站点上执行静默身份验证:

fetch('http://localhost:8100/auth/realms/master/protocol/openid-connect/auth?response_type=code&scope=openid&client_id=portal&redirect_uri=http%3A//localhost%3A8080/o/auth/oidc/callback&state=CJOREX0_bHtivjgNUYRkE3908LqdnUUvm2Jhxo5U8tg&nonce=MJj2eQkCtlwqIx0UbSFdWRsbll7fiBSUkRkbxzi2VFs&prompt=none', {
    method: 'GET',
    mode: 'cors'
})

我已经为我的客户配置了网络源,如下所示:

但我仍然收到 CORS 错误:

Access to fetch at 'http://localhost:8100/auth/realms/master/protocol/openid-connect/auth?response_type=code&scope=openid&client_id=portal&redirect_uri=http%3A//localhost%3A8080/o/auth/oidc/callback&state=CJOREX0_bHtivjgNUYRkE3908LqdnUUvm2Jhxo5U8tg&nonce=MJj2eQkCtlwqIx0UbSFdWRsbll7fiBSUkRkbxzi2VFs&prompt=none' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

知道我错过了什么吗?

整个方法在这里都是错误的。我试图使用来自客户端的 授权码 流程,这不是它应该如何工作的。授权代码流总是关于服务器到服务器与客户端重定向的交互。

如果您想使用它,您需要在 iframe 或单独的页面中打开目标页面(对于静默身份验证,不可见的 iframe 就可以)。

如果您的目标是拥有纯客户端身份验证,您宁愿考虑使用 Implicit(这是经典且简单的,但出于安全原因目前不推荐使用)或带有 PKCE 的授权码 流。

有很多关于身份验证流程的资源,但如果您想快速查看它们的高级概述,我建议您查看这篇简短的文章: https://dev.to/hem/oauth-2-0-flows-explained-in-gifs-2o7a