我有一个带有javascript的html页面,我想自动登录用户。我有以下代码:
var url = "http://localhost:8180/auth/realms/Myrealm/protocol/openid-connect/token";
const response = await fetch(url, {
mode: 'no-cors',
method: "POST",
body: JSON.stringify({
"client_id":"myclientid",
"username":"admin",
"password":"123",
"grant_type":"password"
}),
headers:{
//"Content-type":"application/x-www-form-urlencoded",
"Content-Type": "application/json"
}
})
在keycloak服务器上我添加了Web Origins'*'。我收到以下错误:
POST http://localhost:8180/auth/realms/Myrealm/protocol/openid-connect/token 400(错误请求)
我不知道为什么它不起作用。当我使用终端它工作正常:
curl -i -d "client_id=myclientid" -d "username=admin" -d "password=123" -d "grant_type=password" http://localhost:8180/auth/realms/Myrealm/protocol/openid-connect/token
(keycloak版本4.8.3)
const response = await fetch(url, {
method: "POST",
body: 'client_id=myclientid&password=123&username=admin&grant_type=password',
headers:{
"Content-type":"application/x-www-form-urlencoded"
}
})
我收到以下回复:
它现在正在工作。问题是发送JSON而不是application/x-www-form-urlencoded
并且还获取ReadableStream而不是字符串作为响应。所以这是我现在的代码:
const response = await fetch(url, {
method: "POST",
body: "client_id=myclientid&password=123&username=admin&grant_type=password",
headers:{
"Content-type":"application/x-www-form-urlencoded"
}
});
response.body.getReader().read().then(function (data){
var string = new TextDecoder("utf-8").decode(data.value);
console.log(string);
});