Takkun Takkun - 8 months ago 38
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
contains a specific authority like


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;