1
我想用兩個不同的過濾器配置彈簧安全。 我想要的是有一些URL將被一個過濾器處理,以及一些URL將被其他過濾器處理。 這是我想出了設置:彈簧引導安全 - 兩個不同的過濾器
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled=true)
public class SecurityConfigurationContext {
@Order(1)
@Configuration
public static class ConfigurerAdapter1 extends WebSecurityConfigurerAdapter{
...
@Override
protected void configure(final HttpSecurity http) throws Exception {
// Handlers and entry points
http.exceptionHandling()
.authenticationEntryPoint(MyCustomAuthenticationEntryPoint);
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/filter1-urls/*").hasRole("USER");
http.addFilterBefore(myCustomFilter1, ChannelProcessingFilter.class);
http.csrf().disable();
http.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myCustomAuthenticationService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
@Order(2)
@Configuration
public static class ConfigurerAdapter2 extends WebSecurityConfigurerAdapter{
...
@Override
protected void configure(final HttpSecurity http) throws Exception {
// Handlers and entry points
http.exceptionHandling()
.authenticationEntryPoint(MyCustomAuthenticationEntryPoint);
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/filter2-urls/*").hasRole("SUPER_USER");
http.addFilterBefore(myCustomFilter2, ChannelProcessingFilter.class);
http.csrf().disable();
http.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myCustomAuthenticationService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
}
和過濾器是這樣的:
過濾器1:
@Component
@Order(1)
public final class MyCustomFilter1 implements Filter{
public MyCustomFilter1() {
super();
}
@Override
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
// logic for processing filter1-urls
}
}
過濾器2:
@Component
@Order(2)
public final class MyCustomFilter2 implements Filter{
public MyCustomFilter2() {
super();
}
@Override
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
// logic for processing filter2-urls
}
}
的問題是,無論是這些過濾器在每個請求鏈中都被調用。我提出的任何要求,首先通過一個過濾器,然後通過另一個過濾器,而不是通過一個過濾器。
我該如何解決這個問題?
在此先感謝。
Get請求URL Hmmmm,謝謝。我給它一個嘗試,讓你知道,如果我管理。 – Lazaruss
好的。這個解決方案適用於我。再次感謝。:) – Lazaruss