public class AuthenticationFilter extends GenericFilterBean {
SecureService secureService;
public AuthenticationFilter(SecureService secureService) {
this.secureService=secureService;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest;
Authentication authentication=secureService.getAuthentication(httpServletRequest);
if(authentication!=null) {
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(servletRequest, servletResponse);
SecurityContextHolder.getContext().setAuthentication(null);
}
}
}
@Configuration
@EnableWebSecurity
public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
SecureService secureService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new AuthenticationFilter(secureService), BasicAuthenticationFilter.class)
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/businesses/**").permitAll()
.antMatchers(HttpMethod.GET, "https://stackoverflow.com/users/login").permitAll()
.antMatchers(HttpMethod.POST, "https://stackoverflow.com/users/").permitAll()
.antMatchers(HttpMethod.GET, "/reviews/").permitAll()
.antMatchers(HttpMethod.GET, "/reviews/search").permitAll()
.antMatchers(HttpMethod.GET, "/reviews/**").permitAll()
.antMatchers("/").permitAll().and()
.authorizeRequests().anyRequest().authenticated();
}
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManagerBean();
}
}
這個配置有什麼問題?我跟着這個link寫URL認證。但是我的應用一直阻止所有請求,忽略代碼中指定的所有匹配器。我搜索了一下,有人說規則的順序很重要。但即使我改變了訂單,AuthenticationFilter
一直被調用,並保持阻止所有請求。這個彈簧安全配置爲什麼會阻塞所有路徑?
那是你告訴它做什麼,最後一行覆蓋之前的... –
@ M.Deinum這是不正確的。過濾器被一個接一個讀取。所以如果這些過濾器之前沒有匹配任何其他將需要驗證。 –
只是要確定..你用@Configuration註釋了你的配置? –