@kungfuters是正确的,第一步是确保过滤器首先拦截了该请求。为此,请使用以下web.xml:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher> <!-- Include FORWARD here -->
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
为此,请使用以下Java配置:
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
protected EnumSet<DispatcherType> getSecurityDispatcherTypes() {
return return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC, DispatcherType.FORWARD);
}
}
最后一个是默认情况下,FilterSecurityInterceptor(确保URL受保护的那一部分)将仅拦截REQUEST,而不会拦截其他调度(即转发)。这样做是因为保护转发到的URL很少(通常您会保护进行转发的URL)。为了使您需要在xml配置中使用以下内容,您需要使用http @ once-per-request = true:
<http once-per-request="true">
<!-- ... -->
</http>
同样,在Java配置中有一个afterPerRequest属性可以使用。例如:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.filterSecurityInterceptorOncePerRequest(false)
// make sure to grant access to any login page you are forwarding to
.antMatchers("/restricted/login").permitAll()
.antMatchers("/restricted/**").hasRole("admin")
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll()
// etc
;
}