问题
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