/** * Returns the username from the given {@link KeycloakAuthenticationToken}. By default, this * method resolves the username from the token's {@link KeycloakPrincipal}'s name. This value can * be controlled via <code>keycloak.json</code>'s <a * href="http://docs.jboss.org/keycloak/docs/1.2.0.CR1/userguide/html/ch08.html#adapter-config"> * <code>principal-attribute</code></a>. For more fine-grained username resolution, override this * method. * * @param token the {@link KeycloakAuthenticationToken} from which to extract the username * @return the username to use when loading a user from the this provider's {@link * UserDetailsService}. * @see UserDetailsService#loadUserByUsername * @see KeycloakAccount#getPrincipal */ protected String resolveUsername(KeycloakAuthenticationToken token) { Assert.notNull(token, "KeycloakAuthenticationToken required"); Assert.notNull( token.getAccount(), "KeycloakAuthenticationToken.getAccount() cannot be return null"); KeycloakAccount account = token.getAccount(); Principal principal = account.getPrincipal(); return principal.getName(); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) super.authenticate(authentication); String username; UserDetails userDetails; if (token == null) { return null; } username = this.resolveUsername(token); userDetails = userDetailsService.loadUserByUsername(username); return new KeycloakUserDetailsAuthenticationToken( userDetails, token.getAccount(), token.getAuthorities()); }