I’ve been banging my head against the wall trying to resolve this issue. I’m trying to retrieve the currently logged in user. I have an end-point of /login as shown below. The problem is at line 7. For some odd reason, this line returns null at other end-points but this current one, /login. For example, if I make a post request to /todos, this SecurityContextHolder will return null, but it will not be null in /login. Please help, thank you.
@PostMapping("/login")
1) public ResponseEntity <String> login (@RequestBody LoginDTO loginDTO) {
2) String method = "login ()";
3) logger.info("Entering, " + method);
4) Authentication authenticate = auth.authenticate(new UsernamePasswordAuthenticationToken(loginDTO.getusername(), loginDTO.getpassword())); 5) SecurityContextHolder.getContext().setAuthentication(authenticate);
6) System.out.println("Your authentication object: " + authenticate);
7) String principal = SecurityContextHolder.getContext().getAuthentication().getName(); 8) System.out.println("Principal " + principal);
9) logger.debug(authenticate);
10) return new ResponseEntity <>("Welcome, " + loginDTO.getusername() + "!", HttpStatus.OK); }
I tried researching but seems like there’s very little out there regarding this. I did read that SecurityContextHolder is ThreadLocal variable, meaning that it’s only available for that thread, is there a way I can bypass this? Or perhaps a workaround?