【问题标题】:What is username and password when starting Spring Boot with Tomcat?使用Tomcat启动Spring Boot时的用户名和密码是什么?
【发布时间】:2016-09-14 01:53:09
【问题描述】:

当我通过 Spring Boot 部署我的 Spring 应用程序并访问 localhost:8080 时,我必须进行身份验证,但是用户名和密码是什么或如何设置?我尝试将此添加到我的 tomcat-users 文件中,但没有成功:

<role rolename="manager-gui"/>
    <user username="admin" password="admin" roles="manager-gui"/>

这是应用程序的起点:

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}

这是 Tomcat 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

如何在localhost:8080 上进行身份验证?

【问题讨论】:

  • 你需要认证=你想要认证?因为 spring-boot-starter-tomcat/-web 中没有身份验证,也没有用户名和密码。如果您看到一些,可能是 :8080 上的不同应用程序
  • 它在启动时打印在控制台上。

标签: java spring spring-mvc tomcat spring-boot


【解决方案1】:

首先,只需将以下内容添加到您的 application.properties 文件中

spring.security.user.name=user
spring.security.user.password=pass

注意:没有双引号

运行您的应用程序并输入凭据(用户、密码)

【讨论】:

    【解决方案2】:

    尝试从您的项目中的以下代码片段中获取用户名和密码并登录,希望这会起作用。

    @Override
        @Bean
        public UserDetailsService userDetailsService() {
            List<UserDetails> users= new ArrayList<UserDetails>();
            users.add(User.withDefaultPasswordEncoder().username("admin").password("admin").roles("USER","ADMIN").build());
            users.add(User.withDefaultPasswordEncoder().username("spring").password("spring").roles("USER").build());
            return new UserDetailsManager(users);
        }
    

    【讨论】:

      【解决方案3】:

      当我开始学习 Spring Security 时,我重写了 userDetailsS​​ervice() 方法,如下面的代码 sn-p:

      @Configuration
      @EnableWebSecurity
      public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter{
      
          @Override
          protected void configure(HttpSecurity http) throws Exception {
              http
                      .csrf().disable()
                      .authorizeRequests()
                      .antMatchers("/", "/index").permitAll()
                      .anyRequest().authenticated()
                      .and()
                      .httpBasic();
          }
      
          @Override
          @Bean
          public UserDetailsService userDetailsService() {
              List<UserDetails> users= new ArrayList<UserDetails>();
              users.add(User.withDefaultPasswordEncoder().username("admin").password("nimda").roles("USER","ADMIN").build());
              users.add(User.withDefaultPasswordEncoder().username("Spring").password("Security").roles("USER").build());
              return new InMemoryUserDetailsManager(users);
          }
      }
      

      所以我们可以使用上述凭据登录应用程序。 (例如管理员/nimda)

      注意:我们不应该在生产中使用它。

      【讨论】:

        【解决方案4】:

        覆盖时

        spring.security.user.name=
        spring.security.user.password=
        

        application.properties中,"username" 周围不需要",只需使用username。还有一点,不是存储 原始密码,而是使用 bcrypt/scrypt 加密它并像

        一样存储它
        spring.security.user.password={bcrypt}encryptedPassword
        

        【讨论】:

          【解决方案5】:

          除了接受的答案 -

          如果日志中没有看到密码,请启用“org.springframework.boot.autoconfigure.security”日志。

          如果您微调日志记录配置,请确保 org.springframework.boot.autoconfigure.security 类别设置为日志 INFO 消息,否则不会打印默认密码。

          https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/reference/htmlsingle/#boot-features-security

          【讨论】:

            【解决方案6】:

            您还可以向用户询问凭据并在服务器启动后动态设置它们(当您需要在客户环境中发布解决方案时非常有效):

            @EnableWebSecurity
            public class SecurityConfig {
            
                private static final Logger log = LogManager.getLogger();
            
                @Autowired
                public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
                    log.info("Setting in-memory security using the user input...");
            
                    Scanner scanner = new Scanner(System.in);
                    String inputUser = null;
                    String inputPassword = null;
                    System.out.println("\nPlease set the admin credentials for this web application");
                    while (true) {
                        System.out.print("user: ");
                        inputUser = scanner.nextLine();
                        System.out.print("password: ");
                        inputPassword = scanner.nextLine();
                        System.out.print("confirm password: ");
                        String inputPasswordConfirm = scanner.nextLine();
            
                        if (inputUser.isEmpty()) {
                            System.out.println("Error: user must be set - please try again");
                        } else if (inputPassword.isEmpty()) {
                            System.out.println("Error: password must be set - please try again");
                        } else if (!inputPassword.equals(inputPasswordConfirm)) {
                            System.out.println("Error: password and password confirm do not match - please try again");
                        } else {
                            log.info("Setting the in-memory security using the provided credentials...");
                            break;
                        }
                        System.out.println("");
                    }
                    scanner.close();
            
                    if (inputUser != null && inputPassword != null) {
                         auth.inMemoryAuthentication()
                            .withUser(inputUser)
                            .password(inputPassword)
                            .roles("USER");
                    }
                }
            }
            

            (2018 年 5 月)更新 - 这将适用于 spring boot 2.x:

            @Configuration
            public class SecurityConfig extends WebSecurityConfigurerAdapter {
            
                private static final Logger log = LogManager.getLogger();
            
                @Override
                protected void configure(HttpSecurity http) throws Exception {
                    // Note: 
                    // Use this to enable the tomcat basic authentication (tomcat popup rather than spring login page)
                    // Note that the CSRf token is disabled for all requests
                    log.info("Disabling CSRF, enabling basic authentication...");
                    http
                    .authorizeRequests()
                        .antMatchers("/**").authenticated() // These urls are allowed by any authenticated user
                    .and()
                        .httpBasic();
                    http.csrf().disable();
                }
            
                @Bean
                public UserDetailsService userDetailsService() {
                    log.info("Setting in-memory security using the user input...");
            
                    String username = null;
                    String password = null;
            
                    System.out.println("\nPlease set the admin credentials for this web application (will be required when browsing to the web application)");
                    Console console = System.console();
            
                    // Read the credentials from the user console: 
                    // Note: 
                    // Console supports password masking, but is not supported in IDEs such as eclipse; 
                    // thus if in IDE (where console == null) use scanner instead:
                    if (console == null) {
                        // Use scanner:
                        Scanner scanner = new Scanner(System.in);
                        while (true) {
                            System.out.print("Username: ");
                            username = scanner.nextLine();
                            System.out.print("Password: ");
                            password = scanner.nextLine();
                            System.out.print("Confirm Password: ");
                            String inputPasswordConfirm = scanner.nextLine();
            
                            if (username.isEmpty()) {
                                System.out.println("Error: user must be set - please try again");
                            } else if (password.isEmpty()) {
                                System.out.println("Error: password must be set - please try again");
                            } else if (!password.equals(inputPasswordConfirm)) {
                                System.out.println("Error: password and password confirm do not match - please try again");
                            } else {
                                log.info("Setting the in-memory security using the provided credentials...");
                                break;
                            }
                            System.out.println("");
                        }
                        scanner.close();
                    } else {
                        // Use Console
                        while (true) {
                            username = console.readLine("Username: ");
                            char[] passwordChars = console.readPassword("Password: ");
                            password = String.valueOf(passwordChars);
                            char[] passwordConfirmChars = console.readPassword("Confirm Password: ");
                            String passwordConfirm = String.valueOf(passwordConfirmChars);
            
                            if (username.isEmpty()) {
                                System.out.println("Error: Username must be set - please try again");
                            } else if (password.isEmpty()) {
                                System.out.println("Error: Password must be set - please try again");
                            } else if (!password.equals(passwordConfirm)) {
                                System.out.println("Error: Password and Password Confirm do not match - please try again");
                            } else {
                                log.info("Setting the in-memory security using the provided credentials...");
                                break;
                            }
                            System.out.println("");
                        }
                    }
            
                    // Set the inMemoryAuthentication object with the given credentials:
                    InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
                    if (username != null && password != null) {
                        String encodedPassword = passwordEncoder().encode(password);
                        manager.createUser(User.withUsername(username).password(encodedPassword).roles("USER").build());
                    }
                    return manager;
                }
            
                @Bean
                public PasswordEncoder passwordEncoder() {
                    return new BCryptPasswordEncoder();
                }
            }
            

            【讨论】:

              【解决方案7】:

              如果spring-security jars 被添加到类路径中,并且如果它是spring-boot 应用程序,则所有http 端点都将被默认安全配置类SecurityAutoConfiguration 保护

              这会导致浏览器弹出窗口询问凭据。

              每个应用程序的密码更改都会重新启动,并且可以在控制台中找到。

              Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
              

              要在默认设置之前添加您自己的应用程序安全层,

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

              或者如果你只是想更改密码,你可以覆盖默认值,

              application.xml

              security.user.password=new_password

              application.properties

              spring.security.user.name=<>
              spring.security.user.password=<>
              

              【讨论】:

              • 我刚刚将 spring.security.user.name= spring.security.user.password= 添加到 application.properties 文件中。我没有做任何其他事情。仍然有效。
              • 您在 xml 示例中的属性名称错误 这是 spring.security.user.password=xxx 我们使用 .yml 文件时也不确定 XML 格式
              • 当使用inMemoryAuthentication 时,当您收到错误消息时,您宁愿在密码前加上 {noop}:There is no PasswordEncoder mapped for the id “null”
              • 在 SecurityConfig 类中添加这个 @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance();可以修复没有为id“null”映射PasswordEncoder
              【解决方案8】:

              如果您无法根据其他指向默认密码的答案找到密码,则最近版本中的日志消息措辞更改为

              Using generated security password: <some UUID>
              

              【讨论】:

                【解决方案9】:

                我认为你的类路径上有 Spring Security,然后 Spring Security 会自动配置默认用户和生成的密码

                请查看您的 pom.xml 文件:

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

                如果你的 pom 中有这个,那么你应该有这样的日志控制台消息:

                Using default security password: ce6c3d39-8f20-4a41-8e01-803166bb99b6

                在浏览器提示中,您将导入用户user 和控制台中打印的密码。

                或者如果你想配置spring security你可以看看Spring Boot secured example

                Security部分的Spring Boot参考文档中有解释,它表示:

                The default AuthenticationManager has a single user (‘user’ username and random password, printed at `INFO` level when the application starts up)
                
                Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
                

                【讨论】:

                • 如果您微调日志配置,请确保将org.springframework.boot.autoconfigure.security 类别设置为记录INFO 消息,否则不会打印默认密码。
                • 漂亮。一切都默认为某事。双刃剑。
                • 对于我的情况(spring boot vs:2.0.4)控制台是“使用生成的安全密码:eb7a9e02-b9cc-484d-9dec-a295b96d94ee”
                • 这对我来说也是如此。我正要开始问这个问题。
                • @Marcel 我在类路径中添加了spring security,并且可以看到生成的密码,但是当我通过邮递员在基本身份验证中使用用户名作为用户名,密码作为生成密码时。我正在未经授权。
                猜你喜欢
                • 2011-04-19
                • 2013-03-12
                • 1970-01-01
                • 2020-02-07
                • 2017-02-21
                • 2013-07-28
                • 1970-01-01
                • 2015-05-31
                • 2010-09-28
                相关资源
                最近更新 更多