4

Is it correct to put @Secured annotations on interface methods or on methods within classes implementing the interface? Are there any recommendations for this?

When I dig into the class defining the @Secured annotation, I can see that it has the @Inherited annotation set:

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Secured {
    /**
     * Returns the list of security configuration attributes (e.g. ROLE_USER, ROLE_ADMIN).
     *
     * @return String[] The secure method attributes
     */
    public String[]value();
}

Having read this answer, I guess I can set the @Secured annotation on the interface to consistently enforce authorization over all implementations of the interface.

André Gasser
  • 1,065
  • 2
  • 14
  • 34
  • 1
    As written [here](http://kim.saabye-pedersen.org/2013/05/spring-annotation-on-interface-or-class.html), you can annotate interfaces but it only works "if you are using interface-based proxies." In general, Java annotations are not inherited from interfaces. – pma Oct 30 '17 at 09:11
  • @Andre, If the answer is helpful, then you should accept my answer for fellow user of Stackoverflow. – Ataur Rahman Munna Nov 01 '17 at 11:09
  • 1
    @AtaurRahmanMunna done. thx! – André Gasser Nov 01 '17 at 12:06

1 Answers1

1

In your provided link said, @Transactional is also @Inherited. Lets break down each part of them.

As per spring's developers recommended that use @Transactional annotation with concrete class. You can use @Transactional annotation in interface or a method inside the interface. You can think this will work as you expected if you used interface-based-proxies. Annotation that is not inherited refers that if you are using class-based-proxies then probably transaction attribute are not applied to that interface. So the ultimate object can not covered or wrapped by transactional attribute.

If so, @Secured annotation is @Inherited then this can be used both in interface and its implementation class. From spring docs:

The Secured annotation is used to define a list of security configuration attributes for business methods.

For example:

 @Secured({ "ROLE_USER" })
 public void create(Contact contact);

 @Secured({ "ROLE_USER", "ROLE_ADMIN" })
 public void update(Contact contact);

 @Secured({ "ROLE_ADMIN" })
 public void delete(Contact contact);

So In the bottom line, you may have multiple implementations for an interface. So, keeping your @Secured annotation in interface makes sense.

Ataur Rahman Munna
  • 3,887
  • 1
  • 23
  • 34