[java] Spring Security를 사용하여 Java 코드에서 “hasRole”을 확인하는 방법은 무엇입니까?
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)
사용하기 전에 래퍼를 주입해야합니다.
답변
HttpServletRequest 개체의 isUserInRole 메서드를 사용할 수 있습니다.
다음과 같이 :
public String createForm(HttpSession session, HttpServletRequest request, ModelMap modelMap) {
if (request.isUserInRole("ROLE_ADMIN")) {
// code here
}
}
답변
루프를 사용하여 UserDetails에서 권한을 찾는 대신 다음을 수행 할 수 있습니다.
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
boolean authorized = authorities.contains(new SimpleGrantedAuthority("ROLE_ADMIN"));
답변
보안 컨텍스트를 검색 한 다음 사용할 수 있습니다.
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
protected boolean hasRole(String role) {
// get security context from thread local
SecurityContext context = SecurityContextHolder.getContext();
if (context == null)
return false;
Authentication authentication = context.getAuthentication();
if (authentication == null)
return false;
for (GrantedAuthority auth : authentication.getAuthorities()) {
if (role.equals(auth.getAuthority()))
return true;
}
return false;
}
답변
다음과 같이 hasRole () 메소드를 구현할 수 있습니다-(이것은 다른 버전에 대해서는 확실하지 않은 스프링 보안 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;
}
답변
나는 이것을 사용하고있다 :
@RequestMapping(method = RequestMethod.GET)
public void welcome(SecurityContextHolderAwareRequestWrapper request) {
boolean b = request.isUserInRole("ROLE_ADMIN");
System.out.println("ROLE_ADMIN=" + b);
boolean c = request.isUserInRole("ROLE_USER");
System.out.println("ROLE_USER=" + c);
}
답변
AuthorityUtils 클래스 에서 도움을받을 수 있습니다 . 한 줄로 역할 확인 :
if (AuthorityUtils.authorityListToSet(SecurityContextHolder.getContext().getAuthentication().getAuthorities()).contains("ROLE_MANAGER")) {
/* ... */
}
주의 사항 : 존재하는 경우 역할 계층을 확인하지 않습니다.
