Как добавить новые роли текущему пользователю после входа в систему

Я использую весеннюю безопасность для входа в свой проект. Это мой код:

@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(), но нет никакого установщика или метода добавления для добавления новых ролей.

0
0
46
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Вы можете изменить роли пользователя. У вас должен быть конструктор для userDetails, который расширен от org.springframework.security.core.userdetails.User. Сначала получите исходный объект, а затем манипулируйте им или создайте новый экземпляр.

Это может помочь вам:

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);

Другие вопросы по теме