Jordi
Jordi

Reputation: 23247

Spring security: extract subject from jwt in SecurityContextHolder

I'm trying to get subject from principal.

Currently, I'm using this code:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
    String username = ((UserDetails)principal).getUsername();
} else {
    String username = principal.toString();
}

In fact, principal object class is org.springframework.security.oauth2.jwt.Jwt.

Nevertheless, I was expecting to get the subject of jwt, instead of that I'm getting whole token.

My current configuration works well. I mean, I can authorize methods using @PreAuthorize annotation.

My current configuration is:

@Bean
public SecurityFilterChain securityFilterChain(
    HttpSecurity http
) throws Exception {
    Customizer<OAuth2ResourceServerConfigurer<HttpSecurity>> oauth2Customizer = (config) -> config.jwt();
    return http
        .httpBasic().disable()
        .csrf().disable()
        .formLogin().disable()
        .anonymous().disable()
        .logout().disable()
        .authorizeHttpRequests((authorize) -> authorize
            .antMatchers("/actuator/**").permitAll()
            .antMatchers("/gicar/**").permitAll()
            .anyRequest().authenticated()
        )
        .oauth2ResourceServer(oauth2Customizer)
        .build();
}

Any ideas?

Upvotes: 0

Views: 1698

Answers (1)

Elyorbek Ibrokhimov
Elyorbek Ibrokhimov

Reputation: 1106

Assuming there are no other custom configurations and your token is instance of JwtAuthenticationToken, the subject can be directly extracted from the token itself.

String subject = SecurityContextHolder.getContext().getAuthentication().getName();

According to JwtAuthenticationToken and JwtAuthenticationConverter

Upvotes: 1

Related Questions