Вход в систему бесконечно повторяется с неверными учетными даннымиJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Вход в систему бесконечно повторяется с неверными учетными данными

Сообщение 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







Home |
Login


Login


Error:



Username:


Password:


Login



alert("[[${error}]]"); // Thymeleaf inline expression







Подробнее здесь: https://stackoverflow.com/questions/798 ... redentials
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»