45

我想向任何登录的用户显示内容,如果他们没有登录则隐藏。我正在使用jsp和spring security。

显然,一个家庭解决方案很容易完成。但是实现这一目标的最干净的标准方法是什么?

Spring 安全标签似乎没有很好的方式来允许将来添加新角色。

4

8 回答 8

84

我在以下方面取得了成功:

    <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()andisAuthenticated()表达式组合起来效果很好,可以实现相同的目标。这是一个例子:

<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>
于 2009-11-30T06:19:17.960 回答
29

当前版本(3.1 甚至更早)支持将结果保存到属性中的 var 参数。这样,您可以编写以下代码:

<sec:authorize var="loggedIn" access="isAuthenticated()" />
<c:choose>
    <c:when test="${loggedIn}">
        You are logged in
    </c:when>
    <c:otherwise>
        You are logged out
    </c:otherwise>
</c:choose>
于 2012-08-16T12:39:38.937 回答
12

您可以在标签中使用 Spring EL <sec:authorize />,如下所示:

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

<sec:authorize access="isAuthenticated()">
   YES, you are logged in!
</sec:authorize>
于 2010-11-11T10:11:23.530 回答
7

这个怎么样?- 符合 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>
于 2009-11-20T01:04:45.350 回答
3

怎么样:

<%@ 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>
于 2009-11-09T22:44:34.050 回答
2

我用来编码的最简单的......

<%
if (request.getRemoteUser()== null) {%>  
    <!-- put public-only information-->
<%}%>
于 2012-12-04T10:30:23.893 回答
1

这是我这样做的方法:

<%@ page import="org.springframework.security.context.SecurityContextHolder" %>

<c:if test="<%=SecurityContextHolder.getContext().getAuthentication() != null %>">
    <!-- your secure content here -->
</c:if>

让我知道这是否也适合您...

-aj

于 2009-10-30T03:35:50.310 回答
0

您可以在 jsp spring 安全标签中使用它

request.getUserPrincipal().getName()
于 2017-12-11T18:11:45.893 回答