[英]Keycloak returns CORS Access-Control-Allow-Origin error
I am able to login to Keycloak using the keycloak-js
client, however, when making a fetch
request, I get the following error:我可以使用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.
The post request I am making is我正在发出的帖子请求是
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
}
)
The keycloak settings are密钥斗篷设置是
http://localhost:8080
根 URL: http://localhost:8080
http://localhost:8080
有效的重定向 URI: http://localhost:8080
/
底座 URL: /
*
// but I have also tried http://localhost:8080
and + Web Origins: *
// 但我也试过http://localhost:8080
和 +My app is running on http://localhost:8080我的应用程序在 http://localhost:8080 上运行
I managed to solve the problem.我设法解决了这个问题。 It was the format of the data I was sending to Keycloak.这是我发送给 Keycloak 的数据格式。 I need to URLEncode the FormData adding it to the body of the Fetch request.我需要对 FormData 进行 URLEncode,将其添加到 Fetch 请求的正文中。 Also, was using data
rather than body
in the fetch request.此外,在获取请求中使用data
而不是body
。
Anyway, I solved it by putting all the data into PostMan, getting it working in there and then taking the Auto Code generation that Postman provides to come up with this.无论如何,我通过将所有数据放入 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.