Spring boot resource server principal name

Viewed 663

I have a Keycloak server running. and a spring boot application as a resource server. I can authenticate and get token and the spring boot app will accept the token. but when I want to get the username from the Principal I will get a UUID instead of my email or username. I also added a mapper to my keycloak that maps preferred_username to username. and it's working.

JWT info

  ...
  "scope": "openid profile email",
  "email_verified": true,
  "username": "test@test.com",
  "DOB": "12345",
  "name": "test test",
  "preferred_username": "test@test.com",
  "given_name": "test",
  "family_name": "test",
  "email": "test@test.com"
}

my spring app properties:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://localhost:8080/auth/realms/test
2 Answers
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class JWTSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
    
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Bean
    public KeycloakConfigResolver KeycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }

    /**
     * Defines the session authentication strategy.
     */
    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests(authz -> authz
            .anyRequest().permitAll().permitAll())
          .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
    }
}

Spring Security saves the JWT token as principal to the SecurityContextHolder. For example the following code would return the username that you are looking for.

...
import org.springframework.security.oauth2.jwt.Jwt;
...
@GetMapping(value = "current-user", produces = "application/json")
    ResponseEntity<String> getLoggedInUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Jwt principal = (Jwt) authentication.getPrincipal(); 
        String currentUserName = principal.getClaimAsString("username");
        return new ResponseEntity<String>(currentUserName, HttpStatus.OK);
    }
Related