62

I am developing a REST API using Spring 4. I would like to secure some of the endpoints using Spring Security, but based on what I've read this can be done with either @EnableGlobalMethodSecurity or @EnableWebSecurity. Unfortunately, the documentation that I have found for these don't clearly explain what they do (or how they compare). If I want to secure a Spring REST API with authentication and authorization based on data and relationships declared in a standard relational database, what is the recommended method for achieving this in Spring 4?

Christopher
  • 885
  • 2
  • 10
  • 16

1 Answers1

75

EnableWebSecurity will provide configuration via HttpSecurity. It's the configuration you could find with <http></http> tag in xml configuration, it allows you to configure your access based on urls patterns, the authentication endpoints, handlers etc...

EnableGlobalMethodSecurity provides AOP security on methods. Some of the annotations that it provides are PreAuthorize, PostAuthorize. It also has support for JSR-250. There are more parameters in the configuration for you

For your needs, it's better to mix the two. With REST you can achieve everything you need only by using @EnableWebSecurity since HttpSecurity#antMatchers(HttpMethod,String...) accepts control over Http methods

Gorjan Mishevski
  • 182
  • 3
  • 10
Joao Evangelista
  • 2,407
  • 2
  • 26
  • 37
  • 6
    Can you expand slightly on the last paragraph? What about my needs makes it better to mix the two? – Christopher Apr 18 '15 at 18:45
  • 12
    You can use URL patterns to make decisions of if a resource needs authorization or not, the `GlobalMethodSecurity` will provide in which action a certain user can perform within the method, eg. a User name John is authorized to access `/foo/maria`, but then the `@PreAuthorize` intercepts it, because it has a SpEL telling the user's name must equal the name at path variable. If you need only authorize or not a certain URL `EnableWebSecurity` will provide all you need – Joao Evangelista Apr 18 '15 at 19:13