如何添加一个新用户,而不需要重新启动spring boot

deikduxw  于 2021-07-16  发布在  Java
关注(0)|答案(2)|浏览(374)

在完成启动spring boot之后,spring security的配置无法更新。如何添加新用户或更新用户密码或用户角色而不重新启动spring boot?因为当我使用新密码登录时,页面被重定向到/login?错误页面。

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    MemberMapper memberMapper;

    Logger logger = Logger.getLogger(this.getClass());

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

        http.csrf().disable();
        http.addFilterBefore(new loginFilter(), AnonymousAuthenticationFilter.class).
                authorizeRequests().antMatchers("/","/register/**","/log/**").permitAll();

        http.formLogin().loginPage("/log/toLogin") 
                        .loginProcessingUrl("/log/login") 
                        .usernameParameter("memacc")
                        .passwordParameter("mempwd")
                        .failureHandler(new AppsAuthenticationFailureHandler());;

        http.logout().logoutSuccessUrl("/");

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        List<Members> allMembers = memberMapper.getAllMembers();

        for (Members members : allMembers){
            String[] roleList = members.getRoleList().split(",");
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser(members.getMemacc()).password(new BCryptPasswordEncoder().encode(members.getMempwd())).roles(roleList);
        }

    }
}
oogrdqng

oogrdqng1#

在执行登录过程时,spring boots会将用户配置文件保存在内存中。例如,如果为已登录的用户添加新角色并保存在数据库中,则内存中的用户配置文件不会更改,因此必须更新此数据。
您可以使用:

User user = userService.findById(idUser);
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getRoles()));

使用此命令,可以更新spring安全内存中的用户配置文件。

mm5n2pyu

mm5n2pyu2#

谢谢大家,我找到了解决办法。
...
@启用Web安全
公共类securityconfig扩展了WebSecurityConfigureAdapter{

@Autowired
MyUserDetailsService myUserDetailsService;

Logger logger = Logger.getLogger(this.getClass());

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

    http.csrf().disable();

    http.addFilterBefore(new loginFilter(), AnonymousAuthenticationFilter.class).
            authorizeRequests().antMatchers("/","/register/**","/log/**").permitAll();

    http.formLogin().loginPage("/log/toLogin")
                    .loginProcessingUrl("/log/login") 
                    .usernameParameter("memacc")
                    .passwordParameter("mempwd");
    http.logout().logoutSuccessUrl("/");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(myUserDetailsService);
}

} ...
使用类implement userdetailsservice interface。当用户登录时,验证该用户。
... @服务公共类myuserdetailsservice实现userdetailsservice{

@Autowired
MemberMapper memberMapper;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    Members member = memberMapper.getOneMemberByMemacc(username);
    if(member == null)
        throw new UsernameNotFoundException(username + " not found");
    UserDetails userDetails = User.builder()
            .username(member.getMemacc())
            .password("{noop}" + member.getMempwd())
            .roles(member.getRoleList()).build();
    return userDetails;
}

} ...

相关问题