Как проверить полномочия пользователя или разрешение в Коде Java? Например - я хочу показать или скрыть кнопку для пользователя в зависимости от роли. Существуют аннотации как:
@PreAuthorize("hasRole('ROLE_USER')")
Как сделать его в коде Java? Что-то как:
if(somethingHere.hasRole("ROLE_MANAGER")) {
layout.addComponent(new Button("Edit users"));
}
Spring Security 3.0 имеет этот API.
SecurityContextHolderAwareRequestWrapper.isUserInRole(String role)
Вам придется внедрить оболочку, прежде чем использовать ее.
Как ни странно, я не думаю, что существует стандартное решение этой проблемы, поскольку управление доступом Spring-Security основано на выражениях , а не на java. вы можете проверить исходный код для DefaultMethodSecurityExpressionHandler , чтобы узнать, можете ли вы повторно использовать то, что они там делают
вы можете использовать метод isUserInRole объекта HttpServletRequest.
что-то вроде:
public String createForm(HttpSession session, HttpServletRequest request, ModelMap modelMap) {
if (request.isUserInRole("ROLE_ADMIN")) {
// code here
}
}
Вы можете реализовать метод hasRole (), как показано ниже - (Он протестирован на Spring Security 3.0.x, не уверен в других версиях.)
protected final boolean hasRole(String role) {
boolean hasRole = false;
UserDetails userDetails = getUserDetails();
if (userDetails != null) {
Collection<GrantedAuthority> authorities = userDetails.getAuthorities();
if (isRolePresent(authorities, role)) {
hasRole = true;
}
}
return hasRole;
}
/**
* Get info about currently logged in user
* @return UserDetails if found in the context, null otherwise
*/
protected UserDetails getUserDetails() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDetails userDetails = null;
if (principal instanceof UserDetails) {
userDetails = (UserDetails) principal;
}
return userDetails;
}
/**
* Check if a role is present in the authorities of current user
* @param authorities all authorities assigned to current user
* @param role required authority
* @return true if role is present in list of authorities assigned to current user, false otherwise
*/
private boolean isRolePresent(Collection<GrantedAuthority> authorities, String role) {
boolean isRolePresent = false;
for (GrantedAuthority grantedAuthority : authorities) {
isRolePresent = grantedAuthority.getAuthority().equals(role);
if (isRolePresent) break;
}
return isRolePresent;
}