Search code examples
methodsspring-security

Why secure methods in Spring Security and not just URLs?


  • Is it not enough to secure URLs?
  • Is there a way a user could call an URL without the needed credentials and this is the reason to secure methods?
  • Can you provide a real example why securing methods is necessary and not just URLs?

Solution

  • It is usually enough to secure only URLs in simple cases. Think about method level security as an addition to URL level security. For example a simple check that a user has a particular role to access some URL in your app can be achieved with the aid of URL level security.

    However, there are cases you need more fine-grained security. If you want to allow to access the given product (id=5) only to its creator, you do not get by with URL level security only. But you can achieve this with method level security.

    Consider this URL.

    https://myapp.com/products/5
    

    You can check that a user accessing this URL has role REQUIRED_ROLE.

    <security:intercept-url pattern="/products/**" access="hasRole('REQUIRED_ROLE')" />
    

    If you need to ensure that the user is also the product creator, you need something like this:

    ...
    
    @PreAuthorize("#product.creator == authentication.name")
    public void doSomething(Product product);
    
    ...