Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Collection<? extends GrantedAuthority> roles = auth.getAuthorities();
How can I check if roles
contains a specific authority like "ROLE_ADMIN"
?
Spring security internally uses the getAuthority() method to let voters decide if access is granted or not (we will cover voters in our next article). The most common way to provide granted authorities to a user by implementing custom UserDetailsService that build and return the GrantedAuthorities for our application.
Class SimpleGrantedAuthorityStores a String representation of an authority granted to the Authentication object. See Also: Serialized Form.
Robert's answer is correct if you don't know the implementation of the GrantedAuthority
in the list, as is this:
auth.getAuthorities().stream().anyMatch(ga -> ga.getAuthority().equals("ROLE_ADMIN"))
If however, you know they'll all be SimpleGrantedAuthority
, then you can do this:
auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"))
I don't know of any built-in function, but here is a utility method you could use.
if (userHasAuthority("ROLE_ADMIN")) { ... }
.
public static boolean userHasAuthority(String authority)
{
List<GrantedAuthority> authorities = getUserAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (authority.equals(grantedAuthority.getAuthority())) {
return true;
}
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With