Roles & Authorities
Spring Security distinguishes between authorities, which are arbitrary strings, and roles, which are authorities carrying a prefix. The default prefix is ROLE_. Role names in @RolesAllowed are given without the prefix, and the prefix is added when the granted authorities are checked. So @RolesAllowed("ADMIN") matches the granted authority ROLE_ADMIN.
This matters when writing a custom UserDetailsService or authentication provider, since the authorities have to be created with the prefix included:
Source code
Java
List<GrantedAuthority> authorities = user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.collect(Collectors.toList());The roles() builder method of Spring’s User class adds the prefix for you, whereas authorities() doesn’t. That’s why the examples in this documentation use User.withUsername("admin").roles("ADMIN") to grant the ROLE_ADMIN authority.
|
Warning
|
Missing Prefixes Fail Silently
If the authority is stored as ADMIN instead of ROLE_ADMIN, no error is reported. The role check never matches: views annotated with @RolesAllowed("ADMIN") become inaccessible, and any menu item shown conditionally on that role disappears. If a role check doesn’t behave as expected, log AuthenticationContext.getGrantedAuthorities() and confirm that the authorities carry the prefix.
|
To use a prefix other than ROLE_, or none at all, define a GrantedAuthorityDefaults bean. Vaadin picks up the configured prefix and applies it to the access annotations and to the role-checking methods of AuthenticationContext:
Source code
Java
@Bean
static GrantedAuthorityDefaults grantedAuthorityDefaults() {
return new GrantedAuthorityDefaults(""); // No prefix.
}