登录后如何向当前用户添加新角色

时间:2019-05-14 10:47:58

标签: spring spring-security

我使用spring security在我的项目中登录。这是我的代码:

@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(),但是没有用于添加新角色的设置器或添加方法。

1 个答案:

答案 0 :(得分:0)

您可以更改用户角色。您应该有一个从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);