gpt4 book ai didi

keycloak-rest-api - 来自 rest api 的 Keycloak 登录已被 CORS 阻止

转载 作者:行者123 更新时间:2023-12-04 04:15:01 25 4
gpt4 key购买 nike

我正在尝试使用 keycloak 从本地主机 (localhost:3000) 中的现有登录页面登录。 Keycloak 在另一台主机上运行(http://kchost:38080)。我知道这不是推荐的登录方式,但我需要立即调整现有系统。

尝试 curl :

    curl --location --request POST 'http://kchost:38080/auth/realms/myrealm/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=publictestclient' \
--data-urlencode 'username=myuser' \
--data-urlencode 'password=mypass' \
--data-urlencode 'grant_type=password'

我成功获得了预期的响应(使用 access_token 和 refresh_token)。我无法在浏览器上做同样的事情。该错误与 CORS 有关。

我正在使用 axios,这里是代码:

axios.defaults.httpsAgent = new https.Agent({ rejectUnauthorized: false })
axios.defaults.crossDomain = true;

await axios({
method: "POST",
url: 'http://kchost:38080/auth/realms/myrealm/protocol/openid-connect/token',
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
'Access-Control-Allow-Origin': '*'
},
data: {
client_id: 'publictestclient',
username: 'myuser',
password: 'mypass',
grant_type: 'password',
}
})

错误是:Access to XMLHttpRequest at 'http://kchost:38080/auth/realms/myrealm/protocol/openid-connect/token '来自原产地' http://localhost:3000 ' 已被 CORS 策略阻止:请求 header 字段 access-control-allow-origin 在飞行前响应中不允许 Access-Control-Allow-Headers。

如果我省略 header 'Access-Control-Allow-Origin': '*',错误将变为:Access to XMLHttpRequest at 'http://kchost:38080/auth/realms/myrealm/protocol/openid-connect/token '来自原产地' http://localhost:3000 ' 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin” header 。

在 Keycloak 管理端,客户端具有“public”访问类型以避免“clientSecret”要求。启用直接访问授权已启用。为“web origins”和“valid redirect url”尝试了不同的配置,当前的配置是:

valid redirect url: localhost*
web origins: *

我很确定这是与服务器配置相关的问题。我该如何解决?

最佳答案

有效的重定向 url 应该在前面有 http 或 https。因此,对本地主机有效的可能是:https://localhost/*如果您想确保安全,Web 来源应该类似于 https://localhost。

关于keycloak-rest-api - 来自 rest api 的 Keycloak 登录已被 CORS 阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60885213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com