Spring Security: Specifying HTTP Method In mvcMatchers

Sitewide-10usd300x250 Although method level authorization seems superior in Spring applications, we often use request level authorization for convenience. In other words, we find it more convenient to use mvcMatchers or antMatchers rather then using method authorization. However, when using mvcMatchers, many of us ignore restricting by HTTP method. As an example, below is a sample configuration using mvcMatchers. It would allow 1) / and /signup to be visited by any user, 2) restrict any URL beginning with /admin only to ADMINs, and 3) restrict all other URLs only to authenticated users:

@Override
protected void configure(HttpSecurity http) throws Exception {

	http
		.authorizeRequests()
			.mvcMatchers("/", "/signup").permitAll()
			.mvcMatchers("/admin/**").hasRole("ADMIN")
			.anyRequest().authenticated()
		    .and()
                        ...
}

See any lacuna in the above code? mvcMatcher can also restrict the URLs by HTTP method – a less known feature. For example, if you want to expose just the GET method to the home page, you could actually use .mvcMatchers(HttpMethod.GET, "/").permitAll().

So, let’s practice providing HTTP method to mvcMatchers when possible!

Leave a Reply

Your email address will not be published. Required fields are marked *