Takkun Takkun - 1 year ago 77
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

Answer Source

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;