有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在SpringSecurity4中基于角色授权链接

我正在尝试根据角色授权链接

我的页面:

<c:if test="${pageContext.request.userPrincipal.name==null}">
    <li> <a href="<c:url value="/registration"/>"><span class="glyphicon glyphicon-user">Register</span></a> </li>
    <li> <a href="<c:url value="/login"/>"><span class="glyphicon glyphicon-lock">Login</span></a> </li>    
</c:if>

<c:if test="${pageContext.request.userPrincipal.name!=null}">

     <security:authorize access="ROLE_USER">
         <li><a href="cart.jsp"><span class="glyphicon glyphicon-shopping-cart">CART</span></a></li>
     </security:authorize>

     <li><a href="<c:url value="/j_spring_security_logout"></c:url>">logout</a></li>
</c:if>

我得到以下例外情况:

with root cause
org.springframework.expression.spel.SpelEvaluationException:
    EL1008E:(pos 0): Property or field 'ROLE_USER' cannot be found on object of type 
    'org.springframework.security.web.access.expression.WebSecurityExpressionRoot' - maybe not public?

共 (2) 个答案

  1. # 1 楼答案

    必须使用web安全表达式,请参见Spring Security Reference

    30.2 The authorize Tag

    This tag is used to determine whether its contents should be evaluated or not. In Spring Security 3.0, it can be used in two ways [21]. The first approach uses a web-security expression, specified in the access attribute of the tag. The expression evaluation will be delegated to the SecurityExpressionHandler<FilterInvocation> defined in the application context (you should have web expressions enabled in your <http> namespace configuration to make sure this service is available). So, for example, you might have

    <sec:authorize access="hasRole('supervisor')">
    
        This content will only be visible to users who have the "supervisor" authority in their list of <tt>GrantedAuthority</tt>s.
    
    </sec:authorize>
    

    ROLE_USER不是内置的web安全表达式(请参见Spring Security Reference),请改用hasRole('USER'),请参见^{}

    Determines if the SecurityExpressionOperations.getAuthentication() has a particular authority within Authentication.getAuthorities().

    This is similar to SecurityExpressionOperations.hasAuthority(String) except that this method implies that the String passed in is a role. For example, if "USER" is passed in the implementation may convert it to use "ROLE_USER" instead. The way in which the role is converted may depend on the implementation settings.

  2. # 2 楼答案

    试试这个。。而不是<security:authorize access="ROLE_USER">

    <security:authorize access="hasRole('ROLE_USER')">