Что такое имя пользователя и пароль при запуске Spring Загрузка с Tomcat?
Когда я развертываю приложение Spring через 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
?
Ответы
Ответ 1
Я думаю, что у вас есть Spring Безопасность в вашем пути к классу, а затем Spring безопасность автоматически настраивается с пользователем по умолчанию и сгенерированным паролем
Пожалуйста, загляните в свой файл pom.xml для:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Если у вас это у вас в памяти, вы должны иметь сообщение с консольным журналом:
Using default security password: ce6c3d39-8f20-4a41-8e01-803166bb99b6
И в приглашении браузера вы импортируете пользователя user
и пароль, напечатанный на консоли.
Или, если вы хотите настроить защиту Spring, вы можете взглянуть на Spring пример безопасности для безопасности
В справочной документации Spring в разделе 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
Ответ 2
Если в classpath добавлены файлы spring-security
Spring Spring, а также приложение Spring spring-boot
все конечные точки http будут защищены классом конфигурации SecurityAutoConfiguration
по умолчанию 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=<>
Ответ 3
Таким образом, просто добавив зависимость для начальной загрузки с пружинной загрузкой, базовая безопасность уже настроена по умолчанию.
![enter image description here]()
Мы можем настроить конфигурацию безопасности, написав собственную авторизацию и аутентификацию. Для этого создайте новый класс SecurityConfig, который расширяет WebSecurityConfigurerAdapter и переопределяет его методы.
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("javainuse")
.password("javainuse").roles("USER");
}
Ref - Пример безопасности Spring Boot
Ответ 4
Если вы не можете найти пароль на основе других ответов, которые указывают на пароль по умолчанию, формулировка сообщения журнала в последних версиях изменилась на
Using generated security password: <some UUID>
Ответ 5
Вы также можете запросить у пользователя учетные данные и установить их динамически после запуска сервера (очень эффективно, когда вам нужно опубликовать решение в среде клиента):
@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) Обновление - это будет работать на весенней загрузке 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();
}
}
Ответ 6
Дополнение к принятому ответу -
Если пароль не виден в журналах, включите журналы "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
Ответ 7
При переопределении
spring.security.user.name=
spring.security.user.password=
в application.properties вам не нужно "
вокруг "username"
, просто используйте username
. Другой момент, вместо хранения необработанного пароля, зашифруйте его с помощью bcrypt/scrypt и сохраните его как
spring.security.user.password={bcrypt}encryptedPassword