Dan
Dan

Reputation: 3182

Spring Security - Custom PreAuthorize Annotation?

I'm guessing the answer is no here, but I was wondering if there was a way to create a custom annotation like this:

@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@PreAuthorize("hasAuthority('" + PermissionRequired.value() + "')") //doesn't work
public @interface PermissionRequired {
   String value();
}

So I can do this:

@PermissionRequired("CREATE_USER")
public User createuser(User newUser){
//..
}

But there doesn't seem to be a way to refer to the composing annotation, like I'm doing above. This doesn't look like something @AliasFor would solve, as I'm not using the field directly, I'm concatenating it with another string.

My goal here is to create security annotations that do not require any SpEl.

Upvotes: 3

Views: 1331

Answers (1)

Dan
Dan

Reputation: 3182

JSR-250 to the rescue!

Enable it on your application class:

@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
public class MyApplication {
//..
}

Use their annotation:

@RolesAllowed({"ROLE_CREATE_USER"})
public User createuser(User newUser){
//..
}

It seems to require "ROLE_" prefixes on your authorities, though.

Upvotes: 2

Related Questions