首页 > 解决方案 > 登录后如何为当前用户添加新角色

问题描述

我在我的项目中使用弹簧安全登录。这是我的代码:

@Configuration
@EnableWebSecurity
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
@Qualifier(value = "loginServiceImpl")
private UserDetailsService userDetailsService;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService);
}


@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable()
            .authorizeRequests()

            .antMatchers("/login**", "/js/**", "/css/**")
            .permitAll()
            .antMatchers("/role**")
            .access("hasRole('ADMIN') and hasRole('ROLE')")
             ....
            .anyRequest().authenticated()
            .and()

            .formLogin()
            .loginPage("/login")

            .permitAll()
            .and()
            .logout()
            .permitAll()
            .and().exceptionHandling().accessDeniedPage("/403");
    }
}

@Service
public class LoginServiceImpl implements UserDetailsService {

@Autowired
UserDao loginDao;

@Override
public UserDetails loadUserByUsername(String username) {

    try {
        net.liyan.psc.main.entity.main.User user = loginDao.findByUserNameForLogin(username);

        if (user == null) throw new UsernameNotFoundException("User not found.");

        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
            for (Role role : loginDao.getAllRoleByUser(user)) {
                    grantedAuthorities.add(new SimpleGrantedAuthority(role.getCode()));
                }
            }

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                true,
                true,
                true,
                true,
                grantedAuthorities);
    } catch (UsernameNotFoundException ex) {
        throw new UsernameNotFoundException("User not found.");
    }
   }
}

有用。我可以得到当前用户

UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

用户登录成功后,可以向当前用户(userDetails)添加新角色。我可以获得 userDetails.getAuthorities() 但没有任何 setter 或 add 方法来添加新角色。

标签: springspring-security

解决方案


您可以更改用户的角色。您应该有一个从 org.springframework.security.core.userdetails.User 扩展的 userDetails 的构造函数。首先获取原始对象,然后对其进行操作或创建一个新实例。

这可以帮助您:

UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

Collection<GrantedAuthority> collection =  userDetails.getAuthorities();
collection.add(yourAuthorities);

UserDetails user = new UserDetails(userDetails.getUsername(), userDetails.getPassword(), collection);

final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());

SecurityContextHolder.getContext().setAuthentication(authentication);

推荐阅读