1. 程式人生 > >spring security 基礎入門(配置詳解)

spring security 基礎入門(配置詳解)

<filter>
   <filter-name>springSecurityFilterChain</filter-name>
   <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
   <filter-name>springSecurityFilterChain</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
  • 新增配置檔案spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:sec="http://www.springframework.org/schema/security"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">
    <sec:http>
        <!--路徑'/admin/*'需要許可權ROLE_ADMIN-->
        <sec:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')"/>
        <!--以"/user"開頭的所有路徑需要ROLE_USER許可權-->
        <sec:intercept-url pattern="/user**" access="hasRole('ROLE_USER')" />
        <!--制定自定義的登入路徑為/login,登入後預設跳轉/welcome-->
        <sec:form-login login-page="/login" default-target-url="/welcome" />
        <!--指定使用預設登出頁面,登出後跳轉到/login?logout頁面-->
        <sec:logout logout-success-url="/login?logout"/>
        <!--對於沒有許可權的頁面跳轉到/403路徑-->
        <sec:access-denied-handler error-page="/403" />
        <sec:csrf/>
    </sec:http>
    <sec:authentication-manager>
        <sec:authentication-provider user-service-ref="myUserDetailsService"/>
    </sec:authentication-manager>
    <bean id="myUserDetailsService"
          class="com.springframework.security.userservice.MyUserDetailsService"/>
</beans>
        http段指定了路徑相關的配置。

        Intercept-url 段指定路徑攔截許可權控制的規則,pattern為匹配的路徑模式,access是許可權檢查的表示式,即springSecurity攔截滿足pattern的路徑請求,當用戶許可權滿足access所指定的表示式時才能繼續訪問,否則返回403介面。

        form-login段指定login的配置資訊。Login-page用於指定自定義的登陸介面路徑,default-target-url指定登陸後預設跳轉的路徑。

        Logou段配置登出時的相關資訊。Logout-success-url配置登出之後預設跳轉的頁面

        Access-denied-handler配置無權訪問時的頁面配置。error-page指定使用errorpage的方式提示使用者無權訪問,error-page的引數為一個路徑。

        Csrf 使用者防止使用者偽造表單提交,csrf在表單中使用如下。

<input type="hidden"name="${_csrf.parameterName}"
         value="${_csrf.token}"/>

        Authentication-manager 段配置使用者驗證相關的資訊。

        Authentication-provider為authentication provider的配置,這裡可以使用user-service-ref屬性向其新增一個自定義的userservice用於使用者驗證,自定義的userservice必須實現UserDetailsService介面。

        Authentication-provider中還有一些springSecurity內建的authentication可以選擇,本文就不做詳細介紹了。Authentication-provider中jdbc-user-service元素用於基於資料庫的驗證詳細介紹請參考http://www.mkyong.com/spring-security/spring-security-form-login-using-database/。Authentication-provider中user-service元素用於在配置檔案中靜態指定使用者賬戶資訊。Authentication-provider中ldap-user-service元素用於配置ldap驗證。