I have created login and logout as well as registration for my spring boot 3 application.
The issue now arises when I click the login button, it is using the information from my mysql database to log in since when I enter the incorrect credentials it doesn’t work. It redirects me to my homepage, but it doesn’t actually create a session.
I know this because it sends back a 200 response which is just the default login page for spring security.
I have defined a CustomAuthenticationSuccessHandler as well as SecurityConfig below:
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");
}
SecurityConfig:
@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("https://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();
}
}
The mapping I am using to get the login status is in the AuthenticationController class:
@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";
}
}
}
When I call this using postman or a button in my webpage it simply returns a 200 response saying
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Please sign in</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" integrity="sha384-oOE/3m0LUMPub4kaC09mrdEhIc+e3exm4xOGxAmuFXhBNF4hcg/6MiAXAf5p0P56" crossorigin="anonymous"/>
</head>
<body>
<div class="container">
<form class="form-signin" method="post" action="/api/authenticateUser">
<h2 class="form-signin-heading">Please sign in</h2>
<p>
<label for="username" class="sr-only">Username</label>
<input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
</p>
<p>
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
</p>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>
</body></html>
This is just the default login page for spring security. Any ideas?
I have tried to log in and use different methods for authenticating, I also see no session or cookies in my chrome developer tools so it’s definitely not making any sessions.
Thank you
Nabeel Elberry is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.