I have a Spring Boot application where I'm using HttpSession to store jwt tokens after login. In my AuthController, after successful login, I create a session and store the token in it. However, when I try to access the session in a subsequent request, specifically in the /decode endpoint, the session is null. (To display the logged user's name and email, I want to decode the token and get name and email from that.)
AuthController Code:
@PostMapping("/login")
public ResponseEntity<UserDto> login(@RequestBody CredentialsDto credentialsDto, HttpServletRequest request) {
UserDto userDto = userService.login(credentialsDto);
if (userDto == null) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
}
else {
HttpSession session = request.getSession(true);
session.setAttribute("token", userAuthenticationProvider.createToken(userDto));
return ResponseEntity.ok(userDto);
}
}
@GetMapping("/decode")
public ResponseEntity<?> decodeToken(HttpServletRequest request) {
try {
HttpSession session = request.getSession(false);
if(session != null)
{
UserDto userDto = userAuthenticationProvider.decodeToken((String)session.getAttribute("token"));
return ResponseEntity.ok(userDto);
}
else {
System.out.println("Session is null");
return ResponseEntity.ok(null);
}
} catch (JWTDecodeException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error in decoding token");
}
}
What could be causing the session to be null in subsequent requests, and how can I resolve this issue?
Thank you for your help.