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

方法一、JSP中检查user principal

<c:if test="${pageContext.request.userPrincipal.name != null}">
    <label>
     Hi ${pageContext.request.userPrincipal.name} ! Welcome to our site
    </label>
</c:if>

<c:choose>
  <c:when test="${pageContext.request.userPrincipal.authenticated}">Show something</c:when>
  <c:otherwise>Show something else</c:otherwise>
</c:choose>

方法二、检查角色

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

    <sec:authorize access="hasAnyAuthority('ROLE_ADMIN', 'ROLE_USER')" var="isAuthenticated">
    </sec:authorize>

    <c:out value="${isAuthenticated}"/>

和这个

<sec:authorize access="hasAnyRole('ROLE_ADMIN')">
    <a href="delete/${file.id}">Delete</a>
</sec:authorize>

方法三、 还是查询用户

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

方法四、 使用标签库

<%@taglib uri="http://www.springframework.org/security/tags" prefix="sec"%>
<sec:authorize access="isAuthenticated()">
    <% response.sendRedirect("main"); %>
</sec:authorize>

方法五、 使用注解

需要:<global-method-security secured-annotations="enabled" />

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

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值