Spring Security – Securing URLs By HTTP Method

Sitewide-10usd300x250 A common way to restrict access to URLs when using Spring Security is to configure mvcMatchers (or the old antMatchers).

For example, say you have an e-commerce application with the products visible at the URL http://www.example.com/products/{id}, which should be accessible to everyone.

To allow such access, you’ll code a component extending the WebSecurityConfigurerAdapter, and override its configure method as below:

@Component
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
	
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .mvcMatchers("/products/*").permitAll();
	}
}

Now, say only your managers should be able to update the products – using the same URL, but with HTTP PUT method. In other words, you want to have PUT /products/{id} accessible only to users with MANAGER role.

How to configure this?

You, of course, can use Spring’s method security. But there’s also an easy way – passing the HTTP method as a parameter to mvcMatchers. Here is how to code it:

@Component
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
	
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .mvcMatchers(HttpMethod.GET, "/products/*").permitAll()
            .mvcMatchers(HttpMethod.PUT, "/products/*").hasRole("MANAGER");
	}
}

Happy coding!

Leave a Reply

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