Java 使用Tomcat启动Spring Boot时的用户名和密码是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37285016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is username and password when starting Spring Boot with Tomcat?
提问by Gustavo
When I deploy my Spring application via Spring Boot and access localhost:8080I have to authenticate, but what is the username and password or how can I set it? I tried to add this to my tomcat-usersfile but it didn't work:
当我通过 Spring Boot 部署我的 Spring 应用程序并访问时,localhost:8080我必须进行身份验证,但用户名和密码是什么或如何设置?我试图将其添加到我的tomcat-users文件中,但没有用:
<role rolename="manager-gui"/>
<user username="admin" password="admin" roles="manager-gui"/>
This is the starting point of the application:
这是应用程序的起点:
@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);
}
}
And this is the Tomcat dependency:
这是 Tomcat 依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
How do I authenticate on localhost:8080?
我如何进行身份验证localhost:8080?
采纳答案by Marcel Dias
I think that you have Spring Security on your class path and then spring security is automatically configured with a default user and generated password
我认为您的类路径上有 Spring Security,然后使用默认用户和生成的密码自动配置 Spring Security
Please look into your pom.xml file for:
请查看您的 pom.xml 文件:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
If you have that in your pom than you should have a log console message like this:
如果你的 pom 中有它,那么你应该有一个像这样的日志控制台消息:
Using default security password: ce6c3d39-8f20-4a41-8e01-803166bb99b6
Using default security password: ce6c3d39-8f20-4a41-8e01-803166bb99b6
And in the browser prompt you will import the user userand the password printed in the console.
在浏览器提示中,您将导入user控制台中打印的用户和密码。
Or if you want to configure spring security you can take a look at Spring Boot secured example
或者,如果您想配置 spring 安全性,您可以查看Spring Boot 安全示例
It is explained in the Spring Boot Reference documentationin the Securitysection, it indicates:
它在安全部分的 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
回答by Vino
If spring-securityjars are added in classpath and also if it is spring-bootapplication all http endpoints will be secured by default security configuration class SecurityAutoConfiguration
如果spring-security在类路径中添加 jar 并且如果它是spring-boot应用程序,则所有 http 端点都将通过默认安全配置类进行保护SecurityAutoConfiguration
This causes a browser pop-up to ask for credentials.
这会导致浏览器弹出窗口要求提供凭据。
The password changes for each application restarts and can be found in console.
每个应用程序的密码更改都会重新启动,并且可以在控制台中找到。
Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
To add your own layer of application security in front of the defaults,
要在默认值前面添加您自己的应用程序安全层,
@EnableWebSecurity
public class SecurityConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
or if you just want to change password you could override default with,
或者如果您只想更改密码,您可以使用以下命令覆盖默认值,
application.xml
应用程序.xml
security.user.password=new_password
security.user.password=new_password
or
或者
application.properties
应用程序属性
spring.security.user.name=<>
spring.security.user.password=<>
回答by Naor Bar
You can also ask the user for the credentials and set them dynamically once the server starts (very effective when you need to publish the solution on a customer environment):
您还可以要求用户提供凭据并在服务器启动后动态设置它们(当您需要在客户环境中发布解决方案时非常有效):
@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");
}
}
}
(May 2018) An update - this will work on spring boot 2.x:
(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();
}
}
回答by gdecaso
If you can't find the password based on other answers that point to a default one, the log message wording in recent versions changed to
如果您无法根据指向默认密码的其他答案找到密码,则最近版本中的日志消息措辞更改为
Using generated security password: <some UUID>
回答by Ninad Pingale
Addition to accepted answer -
除了接受的答案 -
If password not seen in logs, enable "org.springframework.boot.autoconfigure.security" logs.
如果在日志中没有看到密码,请启用“org.springframework.boot.autoconfigure.security”日志。
If you fine-tune your logging configuration, ensure that the org.springframework.boot.autoconfigure.security category is set to log INFO messages, otherwise the default password will not be printed.
如果微调日志配置,请确保将 org.springframework.boot.autoconfigure.security 类别设置为 log INFO 消息,否则将不会打印默认密码。
https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/reference/htmlsingle/#boot-features-security
https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/reference/htmlsingle/#boot-features-security
回答by Jemshit Iskenderov
When overriding
覆盖时
spring.security.user.name=
spring.security.user.password=
in application.properties, you don't need "around "username", just use username. Another point, instead of storing raw password, encrypt it with bcrypt/scryptand store it like
在application.properties 中,您不需要"around "username",只需使用username. 另一点,不是存储原始密码,而是用bcrypt/scrypt加密它并像这样存储它
spring.security.user.password={bcrypt}encryptedPassword
回答by VicXj
When I started learning Spring Security, then I overrided the method userDetailsService()as in below code snippet:
当我开始学习 Spring Security 时,我重写了userDetailsService()方法,如下面的代码片段所示:
@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);
}
}
So we can log in to the application using the above-mentioned creds. (e.g. admin/nimda)
因此,我们可以使用上述凭据登录应用程序。(例如管理员/nimda)
Note: This we should not use in production.
注意:我们不应该在生产中使用它。
回答by Manas Ranjan Mahapatra
Try to take username and password from below code snipet in your project and login and hope this will work.
尝试从您的项目中的以下代码片段中获取用户名和密码并登录,希望这会起作用。
@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);
}

