Теперь проблема возникает, когда я нажимаю кнопку входа в систему: для входа в систему используется информация из моей базы данных MySQL, с тех пор как я введите неправильные учетные данные, это не работает. Он перенаправляет меня на мою домашнюю страницу, но на самом деле не создает сеанс.
Я знаю это, потому что он отправляет обратно ответ 200, который является просто страницей входа по умолчанию для Spring Security.< /p>
Я определил CustomAuthenticationSuccessHandler, а также SecurityConfig ниже:
SuccessHandler:
Код: Выделить всё
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private UserService userService;
public CustomAuthenticationSuccessHandler(UserService theUserService) {
userService = theUserService;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
System.out.println("In customAuthenticationSuccessHandler");
String userName = authentication.getName();
System.out.println("userName=" + userName);
User theUser = userService.findByUsername(userName);
// now place in the session
HttpSession session = request.getSession();
session.setAttribute("user", theUser);
// forward to home page
response.sendRedirect("http://localhost:5173");
}
Код: Выделить всё
@Configuration
public class SecurityConfig {
@Bean
public DaoAuthenticationProvider authenticationProvider(UserService userService) {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(userService); //set the custom user details service
auth.setPasswordEncoder(passwordEncoder()); //set the password encoder - bcrypt
return auth;
}
@Bean
public UserDetailsManager userDetailsManager(DataSource dataSource) {
JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource);
jdbcUserDetailsManager.setUsersByUsernameQuery(
"select username, password, enabled from users where username=?"
);
jdbcUserDetailsManager.setAuthoritiesByUsernameQuery(
"select username, role from roles where username = ?"
);
return jdbcUserDetailsManager;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, AuthenticationSuccessHandler customAuthenticationSuccessHandler) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(configurer ->
configurer
.requestMatchers("/api/register/**", "/api/login/**").permitAll()
.anyRequest().authenticated()
).formLogin(form ->
form
.loginProcessingUrl("/api/authenticateUser")
.defaultSuccessUrl("http://localhost:5173/", true)
.successHandler(customAuthenticationSuccessHandler)
.permitAll()
).logout(logout -> logout.permitAll()
.logoutUrl("api/logout")
.logoutSuccessUrl("/")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
)
.exceptionHandling(configurer -> configurer.accessDeniedPage("/accessDenied")
);
return http.build();
}
// Bcrypt encoding for password
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Код: Выделить всё
@CrossOrigin("http://localhost:5173")
@RestController
@RequestMapping("/api/auth")
public class AuthenticationController {
@GetMapping("/checkloginstatus")
public String checkLoginStatus() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
System.out.println("user is logged in");
return "User " + userDetails.getUsername() + "is logged in";
} else {
System.out.println("user is logged out");
return "User is logged out";
}
}
}
Код: Выделить всё
Please sign in
Please sign in
Username
Password
Sign in
Я пытался войти в систему и использовать разные методы аутентификации, но я также не вижу сеансов или файлов cookie в своих инструментах разработчика Chrome, поэтому он определенно не создает никаких сеансов.
Спасибо
Подробнее здесь: https://stackoverflow.com/questions/787 ... ng-created