Я использую загрузку Java Spring и Thymeleaf. При попытке войти в систему с неверными учетными данными страница зависает на несколько минут и сообщает, что страница не работает.
Когда я активирую отладку в application.properties, он постоянно печатает следующий текст
2025-11-14T22:15:24.172+01:00 DEBUG 15420 --- [app] [io-8080-exec-10] o.s.s.a.dao.DaoAuthenticationProvider : Failed to find user 'mike'
2025-11-14T22:15:24.173+01:00 DEBUG 15420 --- [app] [io-8080-exec-10] o.s.s.authentication.ProviderManager : Authentication failed with provider DaoAuthenticationProvider since Bad credentials
Из этого я понимаю, что он постоянно пытается войти в систему снова и снова, когда учетные данные неверны, вместо того, чтобы просто показывать ошибку. Я не знаю, почему он это делает и как это исправить.
Вот моя конфигурация безопасности
package com.labo.app.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import com.labo.app.service.MyUserDetailService;
@Configuration
public class SecurityConfig {
private final MyUserDetailService myUserDetailService;
public SecurityConfig(MyUserDetailService myUserDetailService) {
this.myUserDetailService = myUserDetailService;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers("/logout") // Disable CSRF for logout
)
.authorizeHttpRequests(authorize -> {
authorize.requestMatchers("/css/**", "/js/**", "/images/**").permitAll();
authorize.requestMatchers("/login", "/error/**", "/logout", "/", "/home", "/test-db").permitAll();
authorize.requestMatchers("/admin/**").hasRole("ADMIN");
authorize.requestMatchers("/user/**").hasRole("USER");
authorize.anyRequest().authenticated();
})
.formLogin(formLogin -> formLogin
.loginPage("/login")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/", true) // Make sure this matches your form action
.failureUrl("/login?error") // This should trigger on failure
.permitAll()
)
.logout(logout -> logout
.logoutRequestMatcher(request -> "/logout".equals(request.getRequestURI()) && "GET".equalsIgnoreCase(request.getMethod())) // Allow GET for logout
.logoutSuccessUrl("/login?logout")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.permitAll()
)
.exceptionHandling(exceptions -> exceptions
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
)
.sessionManagement(session -> session
.maximumSessions(1)
.expiredUrl("/login?expired=true")
);
return httpSecurity.build();
}
@Bean
public UserDetailsService userDetailService() {
return myUserDetailService;
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder =
http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder
.userDetailsService(myUserDetailService)
.passwordEncoder(bCryptPasswordEncoder());
return authenticationManagerBuilder.build();
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
Вот мой метод контроллера
@GetMapping("/login")
public String loginPage(@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout,
Model model) {
if (error != null) {
model.addAttribute("error", "Invalid username and password!");
}
if (logout != null) {
model.addAttribute("message", "You have been logged out successfully.");
}
return "login";
}
Вот моя страница входа
Login Page
Home |
Login
Login
Error:
Username:
Password:
Login
alert("[[${error}]]"); // Thymeleaf inline expression
Подробнее здесь: https://stackoverflow.com/questions/798 ... redentials
Вход в систему бесконечно повторяется с неверными учетными данными ⇐ JAVA
Программисты JAVA общаются здесь
-
Anonymous
1763306608
Anonymous
Я использую загрузку Java Spring и Thymeleaf. При попытке войти в систему с неверными учетными данными страница зависает на несколько минут и сообщает, что страница не работает.
Когда я активирую отладку в application.properties, он постоянно печатает следующий текст
2025-11-14T22:15:24.172+01:00 DEBUG 15420 --- [app] [io-8080-exec-10] o.s.s.a.dao.DaoAuthenticationProvider : Failed to find user 'mike'
2025-11-14T22:15:24.173+01:00 DEBUG 15420 --- [app] [io-8080-exec-10] o.s.s.authentication.ProviderManager : Authentication failed with provider DaoAuthenticationProvider since Bad credentials
Из этого я понимаю, что он постоянно пытается войти в систему снова и снова, когда учетные данные неверны, вместо того, чтобы просто показывать ошибку. Я не знаю, почему он это делает и как это исправить.
Вот моя конфигурация безопасности
package com.labo.app.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import com.labo.app.service.MyUserDetailService;
@Configuration
public class SecurityConfig {
private final MyUserDetailService myUserDetailService;
public SecurityConfig(MyUserDetailService myUserDetailService) {
this.myUserDetailService = myUserDetailService;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers("/logout") // Disable CSRF for logout
)
.authorizeHttpRequests(authorize -> {
authorize.requestMatchers("/css/**", "/js/**", "/images/**").permitAll();
authorize.requestMatchers("/login", "/error/**", "/logout", "/", "/home", "/test-db").permitAll();
authorize.requestMatchers("/admin/**").hasRole("ADMIN");
authorize.requestMatchers("/user/**").hasRole("USER");
authorize.anyRequest().authenticated();
})
.formLogin(formLogin -> formLogin
.loginPage("/login")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/", true) // Make sure this matches your form action
.failureUrl("/login?error") // This should trigger on failure
.permitAll()
)
.logout(logout -> logout
.logoutRequestMatcher(request -> "/logout".equals(request.getRequestURI()) && "GET".equalsIgnoreCase(request.getMethod())) // Allow GET for logout
.logoutSuccessUrl("/login?logout")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.permitAll()
)
.exceptionHandling(exceptions -> exceptions
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
)
.sessionManagement(session -> session
.maximumSessions(1)
.expiredUrl("/login?expired=true")
);
return httpSecurity.build();
}
@Bean
public UserDetailsService userDetailService() {
return myUserDetailService;
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder =
http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder
.userDetailsService(myUserDetailService)
.passwordEncoder(bCryptPasswordEncoder());
return authenticationManagerBuilder.build();
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
Вот мой метод контроллера
@GetMapping("/login")
public String loginPage(@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout,
Model model) {
if (error != null) {
model.addAttribute("error", "Invalid username and password!");
}
if (logout != null) {
model.addAttribute("message", "You have been logged out successfully.");
}
return "login";
}
Вот моя страница входа
Login Page
[url=/]Home[/url] |
[url=/login]Login[/url]
Login
[b]Error:[/b]
Username:
Password:
Login
alert("[[${error}]]"); // Thymeleaf inline expression
Подробнее здесь: [url]https://stackoverflow.com/questions/79820508/login-infinitely-retrying-with-bad-credentials[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия