当我通过 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 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 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
如果在类路径中添加了 spring-security
jar,并且如果它是 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");
}
}
或者,如果您只想更改密码,则可以覆盖默认值,
应用程序.xml
security.user.password=new_password
或者
应用程序属性
spring.security.user.name=<>
spring.security.user.password=<>
inMemoryAuthentication
时,您宁愿在收到错误时在密码前加上 {noop}:There is no PasswordEncoder mapped for the id “null”
覆盖时
spring.security.user.name=
spring.security.user.password=
在 application.properties 中,您不需要在 "username"
周围使用 "
,只需使用 username
。还有一点,不是存储 原始密码,而是使用 bcrypt/scrypt 对其进行加密并将其存储为
spring.security.user.password={bcrypt}encryptedPassword
如果您无法根据指向默认密码的其他答案找到密码,则最近版本中的日志消息措辞更改为
Using generated security password: <some UUID>
您还可以向用户询问凭据并在服务器启动后动态设置它们(当您需要在客户环境中发布解决方案时非常有效):
@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();
}
}
除了接受的答案 -
如果日志中未显示密码,请启用“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
首先,只需将以下内容添加到您的 application.properties 文件中
spring.security.user.name=user
spring.security.user.password=pass
注意:没有双引号
运行您的应用程序并输入凭据(用户、密码)
从 Spring Security 版本 5.7.1 开始,默认用户名是 user
,密码是随机生成的并显示在控制台中(例如 8e557245-73e2-4286-969a-ff57fe326336
)。
请参阅文档以获取更多详细信息:
https://docs.spring.io/spring-security/reference/servlet/getting-started.html
当我开始学习 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);
}
}
因此我们可以使用上述凭据登录应用程序。 (例如管理员/nimda)
注意:我们不应该在生产中使用它。
尝试从您项目中的以下代码片段中获取用户名和密码并登录,希望这能奏效。
@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);
}
org.springframework.boot.autoconfigure.security
类别设置为记录 INFO 消息,否则将不会打印默认密码。