Neo
Neo

Reputation: 3705

Spring Security: move method security annotations out of code

I have gone through the Spring Security video on this page.

Around 36:30 he talks about securing methods using security annotations along with the method signature as shown below:

@Secured("ROLE_USER")
public String create();

Why do we need to keep the annotations along with the method? (since security annotations do not have anything to do with what the method does)

Can I get these annotations out into a separate file so that I can change them without modifying the actual code? (probably using something like Spring AOP features)

Upvotes: 2

Views: 125

Answers (1)

Maksym Demidas
Maksym Demidas

Reputation: 7817

Yes, you can do it thanks to Spring AOP:

<global-method-security>
    <protect-pointcut expression="execution(* com.domain.service.*.*(..))" access="ROLE_USER"/>
</global-method-security>

Ajust expression to your needs.

XML declarations are good from flexibility point of view. Consider following cases:

  • you want to reuse some service in two modules but you want to have different security rules.
  • you want apply some security restriction on per package basis

It is possible only with XML.

Annotations are good from readability point of view. When you see some method then you can view all security restrictions directly. No need to open some XML file each time and think about expressions (is it applied for this method?). So it's easy.

Do not mix both approaches. It's so confusing. Check your needs and choose the best one for you project.

Upvotes: 1

Related Questions