Takkun Takkun - 4 months ago 12
Java Question

How to check if authority exists in a collection of GrantedAuthority?

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Collection<? extends GrantedAuthority> roles = auth.getAuthorities();


How can I check if
roles
contains a specific authority like
"ROLE_ADMIN"
?

Answer

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;
}