首页 > 解决方案 > 使用 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"
    }
})

我得到以下回复:

回复

标签: javascriptkeycloak

解决方案


它现在正在工作。问题是发送 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);
    });

推荐阅读