如何使用Spring安全性有条件地向登录用户显示jsp内容
-
08-07-2019 - |
题
我想向任何登录的用户显示内容,如果他们没有登录则要隐藏。我正在使用jsp和spring安全性。
显然,家庭种植的解决方案很容易完成。但实现这一目标的最简洁的标准方法是什么?
Spring安全标记似乎没有很好的方法可以在将来添加新角色。
解决方案
我在以下方面取得了成功:
<sec:authorize ifAnyGranted="ROLE_ANONYMOUS">
<td><a href="<c:url value="/login.htm"/>">Login</a></td>
</sec:authorize>
<sec:authorize ifNotGranted="ROLE_ANONYMOUS">
<td><a href="<c:url value="/j_spring_security_logout"/>">Logout</a></td>
</sec:authorize>
可以在不影响逻辑的情况下添加新角色。
为了使这个答案与Spring Security 3保持同步,使用isAnonymous()
和isAuthenticated()
表达式迄今为止在组合方面运行良好,以实现同样的目的。这是一个例子:
<sec:authorize access="isAnonymous()">
<form method="POST" action="<c:url value='j_spring_security_check'/>">
Username: <input name="j_username" type="text" value="${SPRING_SECURITY_LAST_USERNAME}" />
Password: <input name="j_password" type="password" />
<input type="submit" value="Sign in" />
</form>
</sec:authorize>
<sec:authorize access="isAuthenticated()">
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
</sec:authorize>
其他提示
当前版本(3.1甚至更早)支持var参数以将结果保存到属性中。通过这种方式,您可以编写以下代码:
<sec:authorize var="loggedIn" access="isAuthenticated()" />
<c:choose>
<c:when test="${loggedIn}">
You are loged in
</c:when>
<c:otherwise>
You are logged out
</c:otherwise>
</c:choose>
您可以在标签<sec:authorize />
中使用Spring EL,如下所示:
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authorize access="isAuthenticated()">
YES, you are logged in!
</sec:authorize>
怎么回事? - 符合Spring 2.5标准; - )
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<security:authorize ifAllGranted="ROLE_USER">
Welcome <%= request.getUserPrincipal().getName() %>
<a href="<c:url value="/j_spring_security_logout"/>">Logout</a><br/>
</security:authorize>
怎么样:
<%@ taglib uri="http://acegisecurity.org/authz" prefix="authz" %>
<c:set var="authenticated" value="${false}"/>
<authz:authorize ifAllGranted="ROLE_USER">
<c:set var="authenticated" value="${true}"/>
</authz:authorize>
<c:if test="${authenticated}">
<!-- your secure content here -->
</c:if>
我用来编码的最简单的......
<%
if (request.getRemoteUser()== null) {%>
<!-- put public-only information-->
<%}%>
以下是我这样做的方式:
<%@ page import="org.springframework.security.context.SecurityContextHolder" %>
<c:if test="<%=SecurityContextHolder.getContext().getAuthentication() != null %>">
<!-- your secure content here -->
</c:if>
让我知道这是否对你有用......
-AJ
你可以在jsp spring security tag中使用它
request.getUserPrincipal().getName()
不隶属于 StackOverflow