This question is a bit old, but this is my take on it:
public enum Role implements GrantedAuthority {
ROLE_USER, ROLE_ADMIN;
@Override
public String getAuthority() {
return name();
}
}
You can then use this together with @PreAuthorize and Spring Expression Language to authorize your methods and classes like so:
@PreAuthorize("hasRole(T(<package name>.Role).ROLE_ADMIN)")
public void doSomeThing() {
...
}
Note: The package name has to be the entire package name (org.company.project) and without the < and >.
As you can see, this isn't type safe per definition, as SpEL expressions are still strings, but IDEs like IntelliJ recognizes them, and will let you know of any errors.
You can use @PreAuthorize with multiple roles using hasAnyRole().
Of course, this may become a bit verbose with many roles, but you can make it prettier by creating your own annotation like this:
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@PreAuthorize("hasRole(T(<package name>.Role).ROLE_ADMIN)")
public @interface AdminAuthorization {
}
Following this, you can authorize your methods like so:
@AdminAuthorization
public void doSomething() {
...
}