Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 410
Takkun Avatar asked Sep 26 '12 23:09

Takkun


People also ask

What is granted authority in Spring Security?

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.

What is SimpleGrantedAuthority in Java?

Class SimpleGrantedAuthorityStores a String representation of an authority granted to the Authentication object. See Also: Serialized Form.


2 Answers

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"))
like image 55
OrangeDog Avatar answered Oct 20 '22 12:10

OrangeDog


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;
}
like image 37
Robert Hanson Avatar answered Oct 20 '22 13:10

Robert Hanson