Spring Security, trailing slashes, and dots in URLs

前端 未结 2 1351
日久生厌
日久生厌 2020-12-16 12:29

I use Spring Security 3.1.4 to secure a Spring MVC 3.2.4 application deployed to Tomcat. I have the following Spring Security configuration:



        
相关标签:
2条回答
  • 2020-12-16 12:55

    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>
    
    0 讨论(0)
  • 2020-12-16 13:17
    <intercept-url pattern="/about/**"...
    

    also works for me in Spring Security 3.1.4. This secures /about, /about/, and /about/anything_else

    0 讨论(0)
提交回复
热议问题