Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Collection<? extends GrantedAuthority> roles = auth.getAuthorities();
如何检查是否roles
包含特定权限,例如"ROLE_ADMIN"
?
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Collection<? extends GrantedAuthority> roles = auth.getAuthorities();
如何检查是否roles
包含特定权限,例如"ROLE_ADMIN"
?
我不知道任何内置函数,但这是您可以使用的实用方法。
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;
}
如果您不知道GrantedAuthority
列表中的实现,罗伯特的回答是正确的,如下所示:
auth.getAuthorities().stream().anyMatch(ga -> ga.getAuthority().equals("ROLE_ADMIN"))
但是,如果您知道它们都将是SimpleGrantedAuthority
,那么您可以这样做:
auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"))