![](/img/trans.png)
[英]Spring security web check if currently authenticated user has role
[英]Spring Security 3 check if user is authenticated
我正在從事舊的Spring 3.0.7項目。 我必須添加任何人都可以訪問的jsp
。 我必須檢查進入此頁面的任何人是經過身份驗證的人還是匿名的人,所以我決定使用此頁面
<security:authorize access="isAuthenticated()">
...
</security:authorize>
<security:authorize access="isAnonymous()">
....
</security:authorize>
向用戶顯示適當的內容。 當我以登錄用戶身份登錄該jsp
時,一切都很好。 當我在沒有登錄的情況下登陸時, isAuthenticated()
不會返回false
而是拋出異常:
java.lang.RuntimeException: org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspException: org.springframework.beans.NotReadablePropertyException: Invalid property 'principal.username' of bean class [org.springframework.security.authentication.AnonymousAuthenticationToken]: Bean property 'principal.username' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
我是Spring的新手,肯定會錯過一些東西。 但是呢
更新
這是我的jsp
相關代碼:
<%@ page isELIgnored="false" contentType="text/html" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<content tag="top">
<security:authorize access="isAuthenticated()">
<!-- authenticated users content -->
</security:authorize>
<security:authorize access="isAnonymous()">
<li><a href="${contextPath}/"><i class="login"></i> Login</a></li>
</security:authorize>
</content>
...
必須添加任何人都可以訪問的jsp?
然后不要將該jsp包含在security.xml文件下面。
在配置元素內部,您可以使用一個或多個元素來限制對特定URL的訪問。 每個元素都指定一個URL模式和一組訪問URL所需的訪問屬性。 請記住,您必須始終在URL模式的末尾包含通配符。 否則,URL模式將無法與具有請求參數的URL匹配。
<security:http auto-config="true" >
<security:intercept-url pattern="/index*" access="ROLE_USER" />
<security:intercept-url pattern="/Transit*" access="ROLE_USER" />
<security:form-login login-page="/login.htm" default-target-url="/index.htm"
authentication-failure-url="/loginerror.htm" />
<security:logout logout-success-url="/logout.htm" />
</security:http>
每當我們要描述沒有任何安全性的url時,我們都應從上述代碼行中安全配置的xml文件下刪除特定的url。 例如,如果我們不需要索引頁的任何安全性,則上面的編碼應如下所示。
<security:http auto-config="true" >
<security:intercept-url pattern="/Transit*" access="ROLE_USER" />
<security:form-login login-page="/login.htm" default-target-url="/index.htm"
authentication-failure-url="/loginerror.htm" />
<security:logout logout-success-url="/logout.htm" />
</security:http>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.