Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@EnableGlobalMethodSecurity vs @EnableWebSecurity

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?

like image 701
Christopher Avatar asked Apr 18 '15 18:04

Christopher


People also ask

What is @EnableGlobalMethodSecurity in spring boot?

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.

What is @EnableWebSecurity in spring boot?

The @EnableWebSecurity is a marker annotation. It allows Spring to find (it's a @Configuration and, therefore, @Component ) and automatically apply the class to the global WebSecurity . If I don't annotate any of my class with @EnableWebSecurity still the application prompting for username and password.

What's the difference between @secured and @PreAuthorize in Spring Security?

@Secured and @RolesAllowed are the same the only difference is @RolesAllowed is a standard annotation (i.e. not only spring security) whereas @Secured is spring security only. @PreAuthorize is different in a way that it is more powerful then the other 2. It allows for SpEL expression for a more fine-grained control.

What prePostEnabled true?

The @EnableGlobalMethodSecurity(prePostEnabled = true) annotation is what enables the @PreAuthorize annotation. This can be added to any class with the @Configuration annotation. I won't go into any depth about them here, but you can also enable @Secured , an older Spring Security annotation, and JSR-250 annotations.


1 Answers

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

like image 83
Joao Evangelista Avatar answered Sep 22 '22 09:09

Joao Evangelista