Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the AccessToken of Keycloak in Spring Boot

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
like image 484
akanzari Avatar asked Oct 23 '25 04:10

akanzari


1 Answers

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

like image 79
Anunay Avatar answered Oct 26 '25 14:10

Anunay