我能够使用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.
我发出的post request是
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设置为
- 根URL:
http://localhost:8080
- 有效的重定向uri:
http://localhost:8080
- 基础网址:
/
- 管理URL:空
- Web起源:
*
//但我也尝试过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));