簡體   English   中英

AuthenticationPrincipal 返回空的 UserDetails object

[英]AuthenticationPrincipal returns empty UserDetails object

我正在嘗試通過 spring 安全性 + jwt 令牌來保護我的 api 端點。 到目前為止,令牌生成器和驗證器運行良好。 當我在方法參數中使用AuthenthicationPrincipal來獲取當前的UserDetails時,就會出現問題。 我的 class Account實現了UserDetails ,我的TokenAuthenticationProvider提供了基於 header 持票人令牌的必要Account

部分配置代碼和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();
    }
}

在調試模式下跟蹤顯示TokenAuthenticationProvider已正確檢索到Account 只有在controller中調用時,才會返回一個空Accountnull屬性)

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

過濾器鏈是正確的:

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
]

我查看了一些教程和問題,但無法推斷出任何合適的答案。

https://octoperf.com/blog/2018/03/08/securing-rest-api-spring-security/ (這激發了我當前的實現)

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

@AuthenticationPrincipal 返回空用戶(這個使用DelegatingFlashMessagesConfiguration在我的情況下不存在)

它與配置或過濾器的順序有關嗎?

要使 @AuthenticationPrincipal 起作用,我需要覆蓋 addArgumentResolvers

@Configuration
public class WevMvcConfiguration extends WebMvcConfigurationSupport {

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

new AuthenticationPrincipalArgumentResolver()使用導入org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver

自定義 class 實現 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    
}

現在工作得很好。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM