How to check "hasRole" in Java Code with Spring Security?
you can use the isUserInRole method of the HttpServletRequest object.
something like:
public String createForm(HttpSession session, HttpServletRequest request, ModelMap modelMap) {
if (request.isUserInRole("ROLE_ADMIN")) {
// code here
}
}
Spring Security 3.0 has this API
SecurityContextHolderAwareRequestWrapper.isUserInRole(String role)
You'll have to inject the wrapper, before you use it.
SecurityContextHolderAwareRequestWrapper
Instead of using a loop to find the authority from UserDetails you can do:
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
boolean authorized = authorities.contains(new SimpleGrantedAuthority("ROLE_ADMIN"));
You can retrieve the security context and then use that:
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;
}