0

我想保護REST API。規則很簡單。使用Spring Security限制端點的身份驗證方法

  • 用戶必須撥打/api/authenticate獲得令牌
  • ,用戶可以使用令牌(從/api/authenticate收到)來訪問API /api/**
  • 端點/api/authenticate只接受HTTP基本身份驗證(無令牌認證)
  • 端點/api/**(不含/api/authenticate)只接受令牌認證(無基本身份驗證)
  • 所有其餘端點是公開的,不需要authe ntication。

實際上我用這樣的:

@Configuration 
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

     @Autowired 
     private TokenAuthenticationProvider tokenAuthenticationProvider; 

     @Override 
     protected void configure(final HttpSecurity httpSecurity) throws Exception { 
      httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 
      httpSecurity.headers().disable(); 
      httpSecurity.setSharedObject(TokenAuthenticationProvider.class, this.tokenAuthenticationProvider); 
      httpSecurity.antMatcher("/api/authenticate").httpBasic(); 
      httpSecurity.antMatcher("/api/**").apply(new TokenAuthenticationConfigurer()); 
      httpSecurity.authorizeRequests() 
        .antMatchers("/api/**").authenticated() 
        .anyRequest().permitAll(); 
     } 
    } 

其實,如果我發送一個請求與令牌/api/authenticate我的配置接受請求。我認爲這是因爲/api/authenticate/api/**的一部分。所以我需要排除這個路徑進行令牌認證。

我該怎麼做?

編輯1

如果我使用.and()流暢的風格,結果是完全一樣的。

@Override 
    protected void configure(final HttpSecurity httpSecurity) throws Exception { 
     httpSecurity.setSharedObject(TokenAuthenticationProvider.class, this.tokenAuthenticationProvider); 
     httpSecurity 
       .headers().disable() 
       .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 
       .and() 
       .antMatcher("/api/authenticate").httpBasic() 
       .and() 
       .antMatcher("/api/**").apply(new TokenAuthenticationConfigurer()) 
       .and() 
       .authorizeRequests().antMatchers("/api/**").authenticated().anyRequest().permitAll(); 
    } 

編輯2

據我所知的SecurityBuilderHttpSecurity),在configure(...)方法的antMatcher(...)每個呼叫將覆蓋先前的呼叫。在調試日誌中,我可以看到,Spring Security始終嘗試將請求路徑與/api/**匹配,但從未再次登錄/api/authenticate。如果我切換訂單,我無法再訪問該API,只需/api/authenticate,因爲Spring Security現在總是嘗試再次匹配/api/authenticate

所以,問題是:我如何可以註冊多個規則:

  • /api/authenticate - >HttpBasicConfigurer.http()
  • /api/** - >TokenAuthenticationConfigurer(我的令牌認證配置,.apply(...)
+0

你管理來解決這個問題? –

+0

是的。您必須通過擴展'WebSecurityConfigurerAdapter'來創建多個安全配置。一個配置爲'/ api/authenticate',另一個爲'/ api/**'。他們每個人都可以配置所需的安全機制。您還必須使用'@ Order'來定義安全配置的優先級。 – baymon

回答

相關問題