Spring Security 4.1+
Spring Security has now added a new matcher which is aware of your Spring MVC URL matching configuration. This tells Spring Security to match paths based on the same rules that Spring MVC uses, eliminating the possibility of a URL being valid, but unsecured.
First you need to replace any old matchers with the new MVC matcher. Spring Security is now in sync with however you have configured Spring MVC so you are free to add or remove any path matching configuration. I recommend sticking with the defaults where possible.
Java Config
If you were using antMatchers
, you now should use mvcMatchers
:
protected configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.mvcMatchers("/about").hasRole("USER");
}
XML Config
You need to add the attribute request-matcher
to your http
tag:
<http request-matcher="mvc">
<intercept-url pattern="/about" access="hasRole('USER')"/>
</http>
Full Reference
Please note that you also should no longer be prefixing your roles with "ROLE_" as Spring Security does this for you automatically.
Spring Security Before 4.1
I've not been able to find a way to handle both trailing slash and path suffixes in Spring Security. Obviously it is possible to write a regexp to handle these cases but this seems to make the security rules overly complex and prone to error. I want to be as confident as possible that I'm not exposing resources accidentally.
Therefore, my approach is to disable this behaviour in Spring by configuring the path matcher to be strict about both trailing slashes and suffixes.
Java Config
@Configuration
public class ServletConfig extends WebMvcConfigurerAdapter {
@Override
public void configurePathMatch(final PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(false);
configurer.setUseTrailingSlashMatch(false);
}
}
XML Config
<mvc:annotation-driven>
<mvc:path-matching suffix-pattern="false" trailing-slash="false" />
</mvc:annotation-driven>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…