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

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

OrangeDog
  • 36,653
  • 12
  • 122
  • 207
Takkun
  • 6,131
  • 16
  • 52
  • 69

2 Answers2

7

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"))
OrangeDog
  • 36,653
  • 12
  • 122
  • 207
6

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;
}
Robert Hanson
  • 579
  • 2
  • 7