Keycloak JavaScript API获取当前登录用户 [英] Keycloak JavaScript API to get current logged in user

查看:630
本文介绍了Keycloak JavaScript API获取当前登录用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们计划使用keycloak来保护一堆Web应用程序,其中一些是用Java编写的,一些是用JavaScript(带有React)的.

We plan to use keycloak to secure a bunch of web apps, some written in Java, some in JavaScript (with React).

在用户通过keycloak登录后,每个Web应用程序都需要检索已登录的用户以及该用户具有的领域/客户端角色.

After the user is logged in by keycloak, each of those web apps needs to retrieve the user that is logged in and the realm/client roles that the user has.

  • 对于Java应用程序,我们尝试了keycloak Java API (request -> KeycloakSecurityContext -> getIdToken -> getPreferredUsername/getOtherClaims).他们似乎工作正常
  • 对于JavaScript应用程序,我们尝试了以下代码,但无法成功将Keycloak初始化(请注意,此操作在Web应用程序代码中,已通过keycloak对用户进行了身份验证,该应用程序仅尝试检索登录的用户扮演什么角色):

  • For Java apps, we tried the keycloak Java API (request -> KeycloakSecurityContext -> getIdToken -> getPreferredUsername/getOtherClaims). They seem to work fine
  • For JavaScript apps, we tried the following code, but could not get Keycloak to init successfully (Note this is in web app code after the user is already authenticated by keycloak, the app is only trying to retrieve who logged in with what roles):

var kc = Keycloak({
    url: 'https://135.112.123.194:8666/auth',
    realm: 'oneRealm',
    clientId: 'main'
}); 

//this does not work as it can't find the keycloak.json file under WEB-INF
//var kc = Keycloak('./keycloak.json'); 

kc.init().success(function () {
    console.log("kc.idToken.preferred_username: " + kc.idToken.preferred_username);
    alert(JSON.stringify(kc.tokenParsed)); 
    var authenticatedUser = kc.idTokenParsed.name; 
    console.log(authenticatedUser);  
}).error(function () {
    window.location.reload();
});

我认为Web应用程序需要检索当前的用户信息是相当普遍的.谁知道上面的代码为什么不起作用?

I assume it would be fairly common that web apps need to retrieve current user info. Anyone knows why the above code didn't work?

谢谢.

推荐答案

    <script src="http://localhost:8080/auth/js/keycloak.js" type="text/javascript"></script>
<script type="text/javascript">
const keycloak = Keycloak({
    "realm": "yourRealm",
    "auth-server-url": "http://localhost:8080/auth",
    "ssl-required": "external",
    "resource": "yourRealm/keep it default",
    "public-client": true,
    "confidential-port": 0,
    "url": 'http://localhost:8080/auth',
    "clientId": 'yourClientId',
    "enable-cors": true
});
const loadData = () => {
    console.log(keycloak.subject);
    if (keycloak.idToken) {
        document.location.href = "?user="+keycloak.idTokenParsed.preferred_username;
        console.log('IDToken');
        console.log(keycloak.idTokenParsed.preferred_username);
        console.log(keycloak.idTokenParsed.email);
        console.log(keycloak.idTokenParsed.name);
        console.log(keycloak.idTokenParsed.given_name);
        console.log(keycloak.idTokenParsed.family_name);
    } else {
        keycloak.loadUserProfile(function() {
            console.log('Account Service');
            console.log(keycloak.profile.username);
            console.log(keycloak.profile.email);
            console.log(keycloak.profile.firstName + ' ' + keycloak.profile.lastName);
            console.log(keycloak.profile.firstName);
            console.log(keycloak.profile.lastName);
        }, function() {
            console.log('Failed to retrieve user details. Please enable claims or account role');
        });
    }
};
const loadFailure =  () => {
     console.log('Failed to load data.  Check console log');
};
const reloadData = () => {
    keycloak.updateToken(10)
            .success(loadData)
            .error(() => {
                console.log('Failed to load data.  User is logged out.');
            });
}
keycloak.init({ onLoad: 'login-required' }).success(reloadData);
</script>

简单的javascript客户端身份验证无框架. 对于仍在寻找的人...

simple javascript client authentication no frameworks. for people who are still looking...

这篇关于Keycloak JavaScript API获取当前登录用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆