Issue
Here is my login. I would implement a logout method with path("/logout")
so that the current user-session go really logout. I am using Spring Security
@POST
@Path("/login")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response login(User credentials) {
if(credentials == null){
return Response.status(Response.Status.BAD_REQUEST).build();
}
try {
User userInfo = new User();
UserDetails userDetails = userDetailsService.loadUserByUsername(credentials.getUsername
// Create authRequest Object with User ind DB, Credentials from Web-client
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userDetails, credentials.getPassword(), userDetails.getAuthorities());
// Authenticate the user
Authentication authentication = authenticationManager.authenticate(authRequest);
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
userInfo.setUsername(authentication.getName());
return Response.status(Response.Status.OK).entity("Login succesfull").build();
}
catch (Exception e) {
SecurityContextHolder.getContext().setAuthentication(null);
return Response.status(Response.Status.UNAUTHORIZED).entity("Login failed").build();
}
}
Solution
@GetMapping("/logout")
public String getLogoutPage(HttpServletRequest request, HttpServletResponse response){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null)
new SecurityContextLogoutHandler().logout(request, response, authentication);
return "redirect:/login";
}
Answered By - ArslanAnjum
Answer Checked By - Senaida (JavaFixing Volunteer)