Merge pull request #12162 from hmdrzsharifi/bael-5249

Bael 5249: Get Keycloak User ID in Spring
This commit is contained in:
Greg Martin 2022-05-19 08:08:06 -04:00 committed by GitHub
commit 6875f86ca2
3 changed files with 22 additions and 0 deletions

View File

@ -24,6 +24,8 @@ public class CustomUserAttrController {
final Principal principal = (Principal) authentication.getPrincipal();
String dob = "";
String userIdByToken = "";
String userIdByMapper = "";
if (principal instanceof KeycloakPrincipal) {
@ -31,6 +33,9 @@ public class CustomUserAttrController {
IDToken token = kPrincipal.getKeycloakSecurityContext()
.getIdToken();
userIdByToken = token.getSubject();
userIdByMapper = token.getOtherClaims().get("user_id").toString();
Map<String, Object> customClaims = token.getOtherClaims();
if (customClaims.containsKey("DOB")) {
@ -39,6 +44,8 @@ public class CustomUserAttrController {
}
model.addAttribute("username", principal.getName());
model.addAttribute("userIDByToken", userIdByToken);
model.addAttribute("userIDByMapper", userIdByMapper);
model.addAttribute("dob", dob);
return "userInfo";
}

View File

@ -0,0 +1,9 @@
### server port
server.port=8080
#Keycloak Configuration
keycloak.auth-server-url=http://localhost:8083/auth
keycloak.realm=baeldung
keycloak.resource=customerClient
keycloak.public-client=true
keycloak.principal-attribute=preferred_username

View File

@ -7,6 +7,12 @@
<h1>
Hello, <span th:text="${username}">--name--</span>.
</h1>
<h1>
User ID By Token: <span th:text="${userIDByToken}">--userID--</span>.
</h1>
<h1>
User ID By Mapper: <span th:text="${userIDByMapper}">--userID--</span>.
</h1>
<h3>
Your Date of Birth as per our records is <span th:text="${dob}" />.
</h3>