如何在spring security中启动服务器后设置新的用户名和密码?

时间:2015-11-04 09:06:24

标签: spring spring-mvc spring-security spring-boot

我创建了一个注册表单并在数据库中添加了用户。但我使用这段代码提供登录工具,该代码仅在服务器启动时运行:

   public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {        
        List<UserEntity> userEntities=userService.getAll();
        for(UserEntity userEntity: userEntities) {
            RoleEntity roleEntity=roleService.getBy(userEntity.getRoleId());
            auth
            .inMemoryAuthentication()
                .withUser(userEntity.getUserName()).password(userEntity.getPassword()).roles(roleEntity.getDescription());
        }

    }
}

如何在配置中添加新用户,以便他们可以在不重新启动服务器的情况下登录?

1 个答案:

答案 0 :(得分:0)

挂钩应用程序启动事件并使用它将用户添加到您的(InMemmory ???)数据库。

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;    

@Component
public class DbInit implements ApplicationListener<ContextRefreshedEvent> {

  @Override
  public void onApplicationEvent(final ContextRefreshedEvent event) {
    //This check is needed, because a typical web application has two contexts,
    //therefore it fires two ContextRefreshedEvent  on startup
    if (isFirstContextRefreshedEvent()) {
       // initYourDatabase
    }
  }

  private boolean done = false;

  /** Return true if this method in this bean is invoked the first time;
       else (second, third... invocation) false. */
  private synconized boolean isFirstContextRefreshedEvent() {
     if (!done) {
       done = false;
       return true;
    } else {
       return false;
    }
  }  
}