在Spring Boot中获取Keycloak的AccessToken [英] Get the AccessToken of Keycloak in Spring Boot
本文介绍了在Spring Boot中获取Keycloak的AccessToken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Spring Boot应用程序中使用Keycloak进行授权管理,我从以下curl命令获取访问令牌:
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
推荐答案
您可以尝试以下代码
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();
我正在使用 2.4.0.Final
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
这篇关于在Spring Boot中获取Keycloak的AccessToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文