简体   繁体   中英

AuthenticationPrincipal returns empty UserDetails object

I'm trying to secure my api endpoints by spring security + jwt token. So far, the token generator and veficator work well. The problem arises when i use AuthenthicationPrincipal in method argument to get current UserDetails . I have my class Account implement UserDetails , and my TokenAuthenticationProvider provide the necessary Account based on header bearer's token.

Partial code of configuration and controller:

@Configuration
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${spring.data.rest.basePath}")
    private String apiBasePath;
    private RequestMatcher protectedUrls;
    private RequestMatcher publicUrls;

    @NotNull
    private final TokenAuthenticationProvider provider;

    @PostConstruct
    private void postConstruct() {
        protectedUrls = new OrRequestMatcher(
                // Api
                new AntPathRequestMatcher(apiBasePath + "/**")
        );
        publicUrls = new NegatedRequestMatcher(protectedUrls);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling()
                // when request a protected page without having authenticated
                .defaultAuthenticationEntryPointFor(forbiddenEntryPoint(),
                        protectedUrls)
                .and()
                // Authenticating with rest requests
                .authenticationProvider(provider)
                .addFilterBefore(restAuthenticationFilter(), // injecting TokenAuthenticationProvider here
                        AnonymousAuthenticationFilter.class)
                .authorizeRequests()
                .requestMatchers(protectedUrls)
                .authenticated()
                .and()
                // Disable server rendering for logging
                .formLogin().disable()
                .httpBasic().disable()
                .logout().disable();
    }
}

Tracing in debug mode shows that the TokenAuthenticationProvider has retrieved correctly the Account . Only when called in the controller, an empty Account is returned ( null attributes)

@RepositoryRestController
@RequiredArgsConstructor
@BasePathAwareController
@RequestMapping(path = "account")
class AccountController {
    @GetMapping("current")
    @ResponseBody
    Account getCurrent(@AuthenticationPrincipal Account account) {
        return account;
    }
}

The filter chain is correct though:

servletPath:/api/account/current
pathInfo:null
headers: 
authorization: Bearer eyJhbGciOiJIUzI1NiIsInppcCI6IkdaSVAi...
user-agent: PostmanRuntime/7.19.0
accept: */*
cache-control: no-cache
postman-token: 73da9eb7-2ee1-43e8-9cd0-2658e4f32d1f
host: localhost:8090
accept-encoding: gzip, deflate
connection: keep-alive


Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  CsrfFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  TokenAuthenticationFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]

I looked into some tutorials and questions but could not deduce any suitable answer.

https://octoperf.com/blog/2018/03/08/securing-rest-api-spring-security/ (which inspires my current implementation)

https://svlada.com/jwt-token-authentication-with-spring-boot/#jwt-authentication

@AuthenticationPrincipal return empty User (this one use DelegatingFlashMessagesConfiguration which does not exist in my case)

Does it have anything to do with the order of configuration or filters?

For @AuthenticationPrincipal to work I need to override addArgumentResolvers

@Configuration
public class WevMvcConfiguration extends WebMvcConfigurationSupport {

    @Override
    protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new AuthenticationPrincipalArgumentResolver());
    }    
}

new AuthenticationPrincipalArgumentResolver() use import org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver

Custom class implement UserDetails

public class UserPrincipal implements UserDetails {

    private static final long serialVersionUID = 1L;    
    private ObjectId id;        
    private String name;    
    private String username;    
    private String email;    
    @JsonIgnore
    private String password;    
    //constructor, getter, etc    
}

Now working really well.

@GetMapping(value="/me")    
    public User getMe(@AuthenticationPrincipal UserPrincipal currentUser){
        logger.debug("name: "+currentUser.getUsername());       
        return this.userService.findByUsername(currentUser.getUsername());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM