1. 程式人生 > >Spring Security教程(2)----SpringSecurity簡單測試

Spring Security教程(2)----SpringSecurity簡單測試

前面講到了SpringSecurity的簡單配置,今天做一個簡單的測試,先看配置檔案

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beansxmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:sec="http://www.springframework.org/schema/security"
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.         http://www.springframework.org/schema/security  
  8.         http://www.springframework.org/schema/security/spring-security-3.1.xsd">
  9.     <!-- 配置不過濾的資源(靜態資源及登入相關) -->
  10.     <sec:httppattern="/**/*.css"security="none"></sec:http
    >
  11.     <sec:httppattern="/**/*.jpg"security="none"></sec:http>
  12.     <sec:httppattern="/**/*.jpeg"security="none"></sec:http>
  13.     <sec:httppattern="/**/*.gif"security="none"></sec:http>
  14.     <sec:httppattern="/**/*.png"security="none"></sec:http>
  15.     <sec:httppattern
    ="/js/*.js"security="none"></sec:http>
  16.     <sec:httppattern="/login.jsp"security="none"></sec:http>
  17.     <sec:httppattern="/getCode"security="none"/><!-- 不過濾驗證碼 -->
  18.     <sec:httppattern="/test/**"security="none"></sec:http><!-- 不過濾測試內容 -->
  19.     <sec:httpauto-config="true">
  20.         <sec:intercept-urlpattern="/app.jsp"access="ROLE_SERVICE"/>
  21.         <sec:intercept-urlpattern="/**"access="ROLE_ADMIN"/>
  22.     </sec:http>
  23.     <sec:authentication-manager>
  24.         <sec:authentication-provider>
  25.             <sec:user-service>
  26.                 <sec:username="admin"password="admin"authorities="ROLE_ADMIN"/>
  27.             </sec:user-service>
  28.         </sec:authentication-provider>
  29.     </sec:authentication-manager>
  30. </beans>

其中

<sec:http pattern="" security="none"></sec:http>

是忽略攔截某些資源的意思,主要是針對靜態資源

<sec:intercept-url pattern="/app.jsp" access="ROLE_SERVICE"/>

表示訪問app.jsp時,需要ROLE_SERVICE許可權

<sec:intercept-url pattern="/**" access="ROLE_ADMIN"/>

表示訪問任何資源都需要ROLE_ADMIN許可權。

注:/**的配置要放到最後,因為如果放到最前面的話就失去了攔截意義,任何只要有ROLE_ADMIN許可權的使用者都可以訪問任何資源,並不會對app.jsp攔截。因為在訪問app.jsp的時候先經過<sec:intercept-url pattern="/**" access="ROLE_ADMIN"/>,、/**又表示任何資源,所以只要具有ROLE_ADMIN許可權就會放行。如果放到最後,先經過<sec:intercept-url pattern="/app.jsp" access="ROLE_SERVICE"/>,這時候訪問app.jsp是就會先判斷使用者是否有ROLE_SERVICE許可權,如果有則放行,反之攔截。

許可權必須已ROLE_開頭,在後面的文章中我們會講到如何修改許可權頭和去掉許可權頭

authentication-manager用來配置使用者管理,在這裡我們定義了一個admin使用者並且具有ROLE_ADMIN許可權,也就是說我們訪問任何資源都可以但是訪問app.jsp時將被攔截

在沒有自定義登入頁面之前,SpringSecurity會自動生成登入頁面,如下圖


然後輸入admin/admin登入


然後訪問app.jsp發現已被spring攔截,說明我們的配置成功了


符:在JSP頁面獲取當前登入的使用者名稱的方法

首先引入taglib

  1. <%@ taglib prefix="sec"uri="http://www.springframework.org/security/tags" %>
然後在jsp頁面中使用下面的方法就可以獲取到使用者名稱了
  1. <sec:authenticationproperty="name"/>
在此僅僅是為了方便測試所以只說下獲取使用者名稱的方法,如何獲取使用者的其他資訊將在後續的章節中講到