我试图使用Keycloak与JavaScript,这些是我所遵循的步骤。
-
我在KeyCloak管理面板中创建了一个客户端。链接到图片
-
我将
.json
文件复制到我的apache文件夹。
{
"realm": "master",
"auth-server-url": "http://localhost:8080/auth",
"ssl-required": "external",
"resource": "test",
"public-client": true,
"confidential-port": 0
}
我去我的index.html和我添加这两行调用脚本。
<script src="keycloak.js"></script> <script> function initKeycloak() { const keycloak = new Keycloak(); keycloak.init().then(function(authenticated) { alert(authenticated ? 'authenticated' : 'not authenticated'); }).catch(function() { alert('failed to initialize'); }); } </script>
这是我在mylogic .js中的内容
var keycloak = new Keycloak();
function initKeycloak() {
keycloak.init({onLoad: 'login-required'}).then(function() {
constructTableRows(keycloak.idTokenParsed);
pasteToken(keycloak.token);
}).catch(function() {
alert('failed to initialize');
});
}
function constructTableRows(keycloakToken) {
document.getElementById('row-username').innerHTML = keycloakToken.preferred_username;
document.getElementById('row-firstName').innerHTML = keycloakToken.given_name;
document.getElementById('row-lastName').innerHTML = keycloakToken.family_name;
document.getElementById('row-name').innerHTML = keycloakToken.name;
document.getElementById('row-email').innerHTML = keycloakToken.email;
}
function pasteToken(token){
document.getElementById('ta-token').value = token;
document.getElementById('ta-refreshToken').value = keycloak.refreshToken;
}
var refreshToken = function() {
keycloak.updateToken(-1)
我试图下载文件keycloak.js,并把它直接放在我的根文件夹,但它发生了同样的问题。这是我打开
页面时得到的消息我对第一点感到困惑,keycloak是否自动从Apache文件夹中的json文件加载配置?让我们假设没有,我认为你的问题在于,你没有传递配置参数给keycloak构造函数。
如何初始化keycloak:
const initKeycloak = async () => {
//you can hardcode these values for now just to see if everything works
const config = { url: 'http://localhost:8080/auth', realm: 'master', clientId: 'test'};
const keycloak = new Keycloak(config);
await keycloak
.init({ onLoad: 'login-required' })
.then(isAuthenticated => {
//user is authenticated
})
.catch(error => { console.log('keycloak error', error); });
}
另一个重要的事情是keycloak-js库版本(在package.json中)必须与keycloak服务器版本匹配。有时不同的版本可以相互工作,但最好的做法是keycloak-js版本与keycloak服务器版本匹配。
你也可以看这里:https://github.com/m-s7/react-core/blob/devel/src/services/keycloak-service.ts这是我的repo与工作keycloak-js实现。