Get the AccessToken of Keycloak in Spring Boot

微笑、不失礼 提交于 2020-08-10 01:15:09

问题


i used Keycloak for the authorization management in my spring boot application, i get the access token from this curl command:

curl \
 -d "client_id=admin-cli" \
 -d "username=user" \
 -d "password=password" \
 -d "grant_type=password" \
 "http://localhost:8180/auth/realms/SpringBootKeycloak/protocol/openid-connect/token"

now i want to get this accessToken in my controller, i tried this example but it doesn't seem to be working, It displays this error :

org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken cannot be cast to org.keycloak.KeycloakPrincipal

回答1:


You can try the following code

        KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) request.getUserPrincipal();        
        KeycloakPrincipal principal=(KeycloakPrincipal)token.getPrincipal();
        KeycloakSecurityContext session = principal.getKeycloakSecurityContext();
        AccessToken accessToken = session.getToken();
        username = accessToken.getPreferredUsername();
        emailID = accessToken.getEmail();
        lastname = accessToken.getFamilyName();
        firstname = accessToken.getGivenName();
        realmName = accessToken.getIssuer();            
        Access realmAccess = accessToken.getRealmAccess();
        roles = realmAccess.getRoles();

I am using 2.4.0.Final

This is along the same line as the example, you can share your piece to understand whats wrong with your bit



来源:https://stackoverflow.com/questions/48432626/get-the-accesstoken-of-keycloak-in-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!