使用Tomcat启动Spring Boot时的用户名和密码是什么?


147

当我通过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上的另一个应用程序
zapl

2
并在启动时打印在控制台上。
克莱里斯-cautiouslyoptimistic-

Answers:


297

我认为您在类路径上具有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安全性,可以看一下Spring Boot安全示例

在Spring Boot Reference文档Security部分中对此进行了说明,它指示:

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

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

美丽。一切都默认为某种东西。双刃剑。
萨钦·夏尔马

1
就我而言(春季启动vs:2.0.4),控制台是“使用生成的安全密码:eb7a9e02-b9cc-484d-9dec-a295b96d94ee”
阿米尔(Amir)

对我来说也是如此。我正要开始提出有关此问题。
Dmitriy Ryabin

@Marcel我已经在类路径中添加了spring安全性,并且可以看到生成的密码,但是当我通过邮递员在基本身份验证中将用户名用作用户名并将密码作为生成密码时使用。我未经授权。
Lokesh Pandey

50

如果将spring-securityjar添加到类路径中,并且如果它是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 =新密码

要么

application.properties

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

我只是将spring.security.user.name = <> spring.security.user.password = <>添加到application.properties文件中。我什么也没做。仍然有效。
Barani r

在xml示例中,您的属性名称错误。spring.security.user.password = xxx由于我们使用.yml文件
因此

使用错误消息时,inMemoryAuthentication您宁可使用{noop}作为密码的前缀:There is no PasswordEncoder mapped for the id “null”
Martin van Wingerden,

将其添加到SecurityConfig类@Bean public PasswordEncoder passwordEncoder(){return NoOpPasswordEncoder.getInstance(); }它可以解决ID为“ null”的映射没有PasswordEncoder的问题
apss1943,

9

覆盖时

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

application.properties,你不需要"周围"username",只是使用username。还有一点,不是存储原始密码,而是使用bcrypt / scrypt对其进行加密,然后像存储它一样

spring.security.user.password={bcrypt}encryptedPassword

3

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

Using generated security password: <some UUID>

2

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

@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();
    }
}


0

当我开始学习Spring Security时,然后覆盖了方法userDetailsS​​ervice(),如下面的代码片段所示:

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

因此,我们可以使用上述凭据登录到应用程序。(例如admin / nimda)

注意:这不应该在生产中使用。


0

尝试从您的项目中的以下代码片段中获取用户名和密码,然后登录,并希望此方法有效。

@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);
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.