2016-11-07 54 views
3
@SuppressWarnings("SpringJavaAutowiringInspection") 
@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private JwtAuthenticationEntryPoint unauthorizedHandler; 

    @Autowired 
    private UserDetailsService userDetailsService; 

    @Autowired 
    public void configureAuthentication(AuthenticationManagerBuilder 
     authenticationManagerBuilder) throws Exception { 
     authenticationManagerBuilder.userDetailsService(userDetailsService); 
    } 

    @Bean 
    public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception { 
     return new JwtAuthenticationTokenFilter(); 
    } 

    @Override 
    protected void configure(HttpSecurity httpSecurity) throws Exception { 
     httpSecurity 
     .csrf().disable() 
     .exceptionHandling() 
      .authenticationEntryPoint(unauthorizedHandler) 
      .and() 
     .sessionManagement() 
      .sessionCreationPolicy(SessionCreationPolicy.STATELESS) 
      .and() 
     .authorizeRequests() 
      .antMatchers("/test").permitAll() 
      .antMatchers("/api/**").permitAll() 
      .anyRequest().authenticated(); 

     httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); 
    } 
} 

我有一個在Spring Security之前運行的自定義過濾器。我希望能夠從篩選器中排除一些URL(例如/test),並且Spring Security和其他人將被攔截(如/api/**)。Spring Security排除了自定義過濾器上的URL

當使用郵遞員測試localhost/test它仍然通過過濾器,即使我有antMatchers("/test").permitAll()

如何繞過過濾器?

回答

3

您可以禁用Spring Security的過濾器鏈的一些網址,看到WebSecurity#ignoring

允許添加RequestMatcher情況下應該是春季安全應該忽略。由Spring Security提供的網絡安全(包括SecurityContext)將不會在HttpServletRequest上提供匹配。通常,註冊的請求應該只有靜態資源。對於動態請求,請考慮將請求映射到允許所有用戶。

實例應用:

webSecurityBuilder.ignoring() 
// ignore all URLs that start with /resources/ or /static/ 
      .antMatchers("/resources/**", "/static/**"); 

因此,可以覆蓋WebSecurityConfigurerAdapter#configure

覆蓋此方法來配置WebSecurity。例如,如果你想忽略某些請求。

+0

@YoungHyunYoo:如果你想排除整個配置,你也可以使用'antMatcher'(而不是'antMatchers'),另請參閱https://stackoverflow.com/questions/35890540/when-to-use-彈簧securitys-antmatcher。 – dur

相關問題