1

I'm trying to understand Spring Security and I'm wondering about creating my own annotations with authorities I've created. I've got something like this:

@PreAuthorize("hasAuthority('STANDARD')")
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface StandardRole {
}
@PreAuthorize("hasAuthority('ADMIN')")
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AdminRole {
}

and actually it looks like:

@AdminRole
@StandardRole
@GetMapping(path = "user", produces = "application/json")
public ResponseEntity<User> getUser(@RequestParam String login) {
   ...
}

but only first annotation works, second one is ommited. I want to do something like @AllowRoles() annotation, for example @Allow({UserType.ADMIN, UserType.STANDARD}) or @Allow({UserType.ADMIN}).

How can I do this? Thanks.

KurdTt-
  • 449
  • 1
  • 5
  • 21

1 Answers1

1

It's a pity to force the door open.

I used jsr250 annotation in my SecurityConfig class:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 ...

@RolesAllowed in my controller:

@RolesAllowed({UserType.TYPE_1, UserType.TYPE_2})
@GetMapping(path = "user", produces = "application/json")
public ResponseEntity<User> getUser() {

Finally, at my CustomDetails implementing UserDetails:

    private static final String PREFIX = "ROLE_";

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Collections.singletonList(
                new SimpleGrantedAuthority(
                        PREFIX + user.getUserType()));
    }

I forgot about "ROLE_" prefix. Code is much cleaner.

KurdTt-
  • 449
  • 1
  • 5
  • 21
  • Upvoted! Thanks for the right suggestion of using the `@RolesAllowed` annotation. Regarding the ROLE_ prefix, one can also decide to strip it from the authorities by overriding ` GrantedAuthorityDefaults` bean desribed here: https://stackoverflow.com/a/43964633/913093 – denu Jul 21 '22 at 13:42