【问题标题】:Spring Security: How to change default user and password?Spring Security:如何更改默认用户和密码?
【发布时间】:2018-01-15 08:16:35
【问题描述】:

我的 pom.xml 中有 Spring Security,Spring Security 自动配置了默认用户和生成的密码:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

如何更改默认用户和密码?

【问题讨论】:

标签: java spring spring-boot


【解决方案1】:

这是straight from the docs

创建一个配置类:

@Configuration
@EnableWebSecurity
public class HelloWebSecurityConfiguration
   extends WebSecurityConfigurerAdapter {

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) {
    auth
      .inMemoryAuthentication()
        .withUser("user").password("password").roles("USER");
  }
}

Newer Docs

这有点不同,但效果是一样的:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService() throws Exception {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("user").password("password").roles("USER").build());
        return manager;
    }
}

【讨论】:

  • 2013 年 7 月 3 日旧文档:'(
  • 我刚刚用 1.5.6 成功地做到了。
【解决方案2】:

这可以在您的 application.properties 文件中轻松完成:

spring.security.user.name=user # Default user name.
spring.security.user.password= # Password
spring.security.user.role= # A comma separated list of roles

这里是documentation

【讨论】:

  • 这在使用Spring Boot 2.2.2.RELEASE和安全依赖时不起作用,我们需要实现configure(...)并扩展WebSecurityConfigurerAdapter
【解决方案3】:
#add these lines in application.properties
    spring.security.user.name=username
    spring.security.user.password=password

【讨论】:

    【解决方案4】:

    application.properties中添加以下属性

    spring.security.user.name= user_name
    spring.security.user.password= user_password
    

    其中“user_name”是用户,“user_password”是密码。

    【讨论】:

      【解决方案5】:

      这些不适用于旧版本的 spring boot,我使用的是 1.5.11.RELEASE 并且这些属性不起作用,移动到 2.1.8.RELEASE 后,这些属性可以正常工作。

      检查你的 pom.xml

      <parent>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-parent</artifactId>
              <version>2.1.8.RELEASE</version>
              <relativePath/> <!-- lookup parent from repository -->
          </parent>
      
      spring.security.user.name=username
      spring.security.user.password=password
      

      【讨论】:

        猜你喜欢
        • 2016-01-02
        • 2019-03-23
        • 2014-09-13
        • 1970-01-01
        • 2013-11-23
        • 1970-01-01
        • 2014-10-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多