javascript - 使用 API 进行 Keycloak 登录
问题描述
我有一个带有 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);
});
推荐阅读
- python - 每次执行后使用不同名称创建文件夹
- sql - 如何使用纬度和经度找到两点之间的距离
- c# - 无法在不同项目之间共享 ResourceDictionary
- c# - 使用 C# 的当前应用程序的活动时间
- javascript - 如何创建自定义钩子,其工作方式类似于 React with Typescript 中的类组件中的 setState
- matlab - 说话人识别系统中的欧几里得距离
- reactjs - 如何将选项卡导航器标题减少到状态栏?
- php - PHP - 从 XML 标记中删除前导和尾随空格
- html - 如果我们的文件名不是 index.html,为什么找不到浪涌显示页面?
- python - 我正在尝试使用 python 的 webbrowser 模块在 chrome 中打开 DINO Game