SpringSecurity web.ignoring()不起作用分析
原因分析
例如:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**");
web.ignoring().antMatchers("/js/**");
web.ignoring().antMatchers("/fonts/**");
}
虽然在WebSecurity.ignoring().antMatchers()中配置了自己要放行的地址,但是我定义了自定义的过滤器。然而自定义过滤器交给了spring IOC管理,所以你在spring Security的config无论怎么配都会走到自己的过滤器。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
// .requestMatchers()//用于规定哪些路径我需要拦截,精确指定请求匹配规则,如特定URL路径、请求方法、请求参数等。
// .antMatchers("/api/**") // 仅匹配 /api/** 路径的请求
// .and()
.authorizeRequests()//基于请求匹配规则来定义访问控制策略。该方法允许您为特定的请求路径或请求模式指定访问要求,如需要特定角色或权限才能访问。
.antMatchers(HttpMethod.DELETE, "/tasks/**").hasRole("ADMIN")
// 测试用资源,需要验证了的用户才能访问
.antMatchers("/tasks/**").authenticated()
// 其他都放行了
.anyRequest().permitAll()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
// 不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling().authenticationEntryPoint(new JWTAuthenticationEntryPoint())
.accessDeniedHandler(new JWTAccessDeniedHandler()); //添加无权限时的处理
}
解决方法
1. 在自己的过滤器中再次设置白名单
请注意如若只在自己的过滤器中设置白名单还不行,因为请求还会走SpringSecurity的过滤器链,必须两边都配置。
如果只想配置一边,可以在自己过滤器放行请求时,直接给本次请求设置一个默认的认证身份
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken
(RoleType.ANONYMOUS.getChineseName(), null, Collections.singleton
(new SimpleGrantedAuthority(
String.valueOf(RoleType.ANONYMOUS.getValue())))));