Spring Security判断用户是否已经登录

方法一、JSP中检查user principal


    



  Show something
  Show something else

方法二、检查角色

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

    
    

    

和这个


    Delete

方法三、 还是查询用户

Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
if (!(auth instanceof AnonymousAuthenticationToken)) { 
     // do something...
}

方法四、 使用标签库

<%@taglib uri="http://www.springframework.org/security/tags" prefix="sec"%>

    <% response.sendRedirect("main"); %>

方法五、 使用注解

需要:

@Secured("ROLE_ADMIN")
@RequestMapping(params = "onlyForAdmins")    
public ModelAndView onlyForAdmins() {
    ....
}

 @PreAuthorize("isAuthenticated()")
 @RequestMapping(params = "onlyForAuthenticated")
 public ModelAndView onlyForAuthenticatedUsers() {
     ....
 }

方法六、 编程

 SecurityContextHolder.getContext().getAuthentication() != null &&
 SecurityContextHolder.getContext().getAuthentication().isAuthenticated() &&
 //when Anonymous Authentication is enabled
 !(SecurityContextHolder.getContext().getAuthentication() 
          instanceof AnonymousAuthenticationToken) 


if (SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
  System.out.println("LOGGED IN");
  } else {
  System.out.println("NOT LOGGED IN");
}


if (!SecurityContextHolder.getContext().getAuthentication().getName().
  equals("anonymousUser")) {
  System.out.println("LOGGED IN");
  } else {
  System.out.println("NOT LOGGED IN");
}

你可能感兴趣的:(Spring Security判断用户是否已经登录)