【问题标题】:Keycloak returns CORS Access-Control-Allow-Origin errorKeycloak 返回 CORS Access-Control-Allow-Origin 错误
【发布时间】:2021-05-12 20:09:59
【问题描述】:

我可以使用 keycloak-js 客户端登录 Keycloak,但是,在发出 fetch 请求时,我收到以下错误:

Access to fetch at 'https://xxxxxxxx.com/auth/realms/app_testing/protocol/openid-connect/token' 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.

我的发帖请求是

var formData = new FormData()
formData.append("client_id", 'vue_blog_gui');
formData.append("grant_type", "password");
formData.append("client_secret", "705669d0-xxxx-xxxx-xxxx-4f4e52e3196b");
formData.append("scope", "openid");
formData.append("username", "user@example.com")
formData.append("password", "123")

fetch(
  'https://xxxxxxxx.com/auth/realms/app_testing/protocol/openid-connect/token',
  {
    method: 'POST',
    'Content-Type': 'application/x-www-form-urlencoded',
    data: formData
  }
)

keycloak 设置是

  • 根网址:http://localhost:8080
  • 有效的重定向 URI:http://localhost:8080
  • 基本网址:/
  • 管理 URL:空
  • Web Origins: * // 但我也尝试过 http://localhost:8080 和 +

我的应用在 http://localhost:8080 上运行

【问题讨论】:

  • @dreamcrash 我尝试了你所有的建议,但仍然遇到相同的 CORS 错误。
  • 很抱歉听到这个消息,顺便说一句,由于安全问题,不建议将 Web Origins: 设置为 *
  • 您尝试过i.stack.imgur.com/F27FK.png 吗?
  • @dreamcrash 我同意,但这只是为了节省人们询问我是否尝试过使用 * 作为来源的时间。哈哈
  • 顺便说一句:直接访问授权不是很安全的身份验证方法。 SPA(例如 Vue)应该使用带有 PKCE 的授权代码流(基本的 vue 示例,但没有 PKCE keycloak.org/securing-apps/vue)。我知道每个 SPA 开发人员都会告诉我这对他更好,因为他将拥有自己精美的 SPA UI,而不是丑陋的 Keycloak 登录表单。 Np,请记住您的优先级是 UI 还是安全。

标签: javascript vue.js cors keycloak keycloak-services


【解决方案1】:

我设法解决了这个问题。这是我发送给 Keycloak 的数据格式。我需要对 FormData 进行 URLEncode,将其添加到 Fetch 请求的正文中。此外,在获取请求中使用了data 而不是body

无论如何,我通过将所有数据放入 PostMan,让它在那里工作,然后使用 Postman 提供的自动代码生成来解决这个问题。

var myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/x-www-form-urlencoded');

var urlencoded = new URLSearchParams();
urlencoded.append('client_id', 'vue_blog_gui');
urlencoded.append('username', 'me@example.com');
urlencoded.append('password', 'password');
urlencoded.append('grant_type', 'password');
urlencoded.append('scope', 'openid');
urlencoded.append('client_secret', '705669d0-xxxx-xxxx-xxxx-4f4e52e3196b');

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: urlencoded,
  redirect: 'follow',
};

fetch(
  'https://keycloak.server.example.com/auth/realms/app_testing/protocol/openid-connect/token',
  requestOptions
)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log('error', error));

【讨论】:

  • 很高兴你已经弄明白了。
  • 老实说 -> 你真的拯救了我的复活节,谢谢! :D
猜你喜欢
  • 1970-01-01
  • 2021-06-17
  • 2016-09-30
  • 2021-10-09
  • 2015-08-17
  • 2014-08-11
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
相关资源
最近更新 更多