Я загрузил роли из базы данных для текущего пользователя. И я могу получить доступ к роли пользователя с выражением безопасности spring в jsp и может скрывать параметры и URL-адреса, которые не разрешены с помощью hasRole. Теперь я хотел иметь его в сервлете и отображать его в журналах (или хранить в сеансе пользовательских объектов). Как мы можем добиться этого?
Как получить текущие роли пользователя из spring security 3.1
Ответ 1
Вы можете попробовать что-то вроде этого:
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
У вас есть набор ролей в переменной полномочий.
Обновление: Исправлена опечатка общего ресурса GrantedAuthority
Ответ 2
Вы пытались вызвать getUserPrincipal() из HttpServletRequest?
Ответ 3
Если вы разрабатываете Java 8, это становится легче.
Чтобы получить все роли пользователя:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Set<String> roles = authentication.getAuthorities().stream()
.map(r -> r.getAuthority()).collect(Collectors.toSet());
чтобы проверить, имеет ли пользователь конкретную роль, например. ROLE_USER:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
boolean hasUserRole = authentication.getAuthorities().stream()
.anyMatch(r -> r.getAuthority().equals("ROLE_USER"));
Ответ 4
Чтобы выполнить оба ответа...
Вот реализация безопасности Spring
getUserPrincipal
, поэтому вы можете видеть, что getUserPrincipal
на самом деле мы SecurityContextHolder
public Principal getUserPrincipal() {
Authentication auth = getAuthentication();
if ((auth == null) || (auth.getPrincipal() == null)) {
return null;
}
return auth;
}
//And the getAuthentication
private Authentication getAuthentication() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!trustResolver.isAnonymous(auth)) {
return auth;
}
return null;
}
Ответ 5
def springSecurityService
def role = springSecurityService.getAuthentication(). getAuthorities()