javascript - Keycloak 返回 CORS Access-Control-Allow-Origin 错误

标签 javascript vue.js cors keycloak keycloak-services

我可以使用 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
  }
)

key 斗篷设置是

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

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

最佳答案

我设法解决了这个问题。这是我发送给 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));

关于javascript - Keycloak 返回 CORS Access-Control-Allow-Origin 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66114861/

相关文章:

typescript - 使用 Vuex mapGetters 时如何修复 TypeScript 错误?

javascript - 如何处理重定向请求以响应在浏览器上下载文件。

django - 使用 django 作为 ionic 应用程序后端时出现 CORS 错误

javascript - HTML Canvas 中的 Z 索引

取消选中特定复选框的 Javascript 代码

javascript - 带参数的 vuexjs getter

javascript - Vuejs : how to manipulate elements using webpack template?

php - 如何在 Woocommerce API 中添加 CORS header

javascript - 如何正确地重用 Mocha 测试的描述 block ?

javascript - 选择没有两个或多个名称的表单