2017-09-23 34 views
-1

這是我的登錄信息。我將使用path("/logout")實現註銷方法,以便當前用戶會話真正註銷。我使用Spring Security的如何使用springboot安全性創建註銷

@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(); 
    } 
} 
+0

那麼,什麼是你的問題? – Ravi

+0

@Ravi我如何編碼註銷? – Manu

回答

0
@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"; 
    } 
+0

基本上它會使會話無效並從安全上下文中清除身份驗證。 – ArslanAnjum