Spring reload the user access groups in a filter
import java.util.*;
import org.springframework.security.core.GrantedAuthority;
import javax.servlet.http.HttpSession;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import de.hybris.platform.servicelayer.session.SessionService;
private static final String SPRING_SECURITY_CONTEXT="SPRING_SECURITY_CONTEXT";
private static final String ROLE="ROLE_";
HttpSession session = httpRequest.getSession(true);
if (session.getAttribute(SPRING_SECURITY_CONTEXT) != null) {
Object contextFromSession = session.getAttribute(SPRING_SECURITY_CONTEXT);
if ((contextFromSession instanceof SecurityContext)) {
Authentication auth = ((SecurityContext) contextFromSession).getAuthentication();
List<GrantedAuthority> updatedAuthorities = new ArrayList<>();
Set<UserGroupModel> userGroups = getUserService().getAllUserGroupsForUser(currentUser);
if(!userGroups.isEmpty()) {
for (UserGroupModel userGroup : userGroups) {
updatedAuthorities.add(new SimpleGrantedAuthority(ROLE+ userGroup.getUid().toUpperCase()));
}
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
auth.getPrincipal(), auth.getCredentials(), updatedAuthorities);
authToken.setDetails(new WebAuthenticationDetails(httpRequest));
((SecurityContext) contextFromSession).setAuthentication(authToken);
session.setAttribute(SPRING_SECURITY_CONTEXT, contextFromSession);
}
}
}
Comments
Post a Comment