How to reload authorities on user update with Spring Security

前端 未结 6 1846
情话喂你
情话喂你 2020-12-04 08:44

I\'m doing an application with authentication by OpenID using Spring Security. When user is logged-in, some authorities are loaded in his session.

I have User with f

6条回答
  •  爱一瞬间的悲伤
    2020-12-04 09:17

    I have a very specific case of above, I use Redis to track user session with https://github.com/spring-projects/spring-session. Then when admin adds some Role to the user I find user session in Redis and replace principal and authorities and then save the session.

    public void updateUserRoles(String username, Set newRoles) {
            if (sessionRepository instanceof FindByIndexNameSessionRepository) {
                Map map =
                        ((FindByIndexNameSessionRepository) sessionRepository)
                                .findByPrincipalName(username);
                for (org.springframework.session.Session session : map.values()) {
                    if (!session.isExpired()) {
                        SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT_KEY);
                        Authentication authentication = securityContext.getAuthentication();
                        if (authentication instanceof UsernamePasswordAuthenticationToken) {
                            Collection authorities = new HashSet<>(authentication.getAuthorities());
                            //1. Update of authorities
                            authorities.addAll(newRoles);
                            Object principalToUpdate = authentication.getPrincipal();
                            if (principalToUpdate instanceof User) {
                                //2. Update of principal: Your User probably extends UserDetails so call here method that update roles to allow
                                // org.springframework.security.core.userdetails.UserDetails.getAuthorities return updated 
                                // Set of GrantedAuthority
                                securityContext
                                        .setAuthentication(new UsernamePasswordAuthenticationToken(principalToUpdate, authentication
                                                .getCredentials(), authorities));
                                session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, securityContext);
                                sessionRepository.save(session);
                            }
                        }
                    }
                }
            }
        }
    

提交回复
热议问题