Spring Security的使用

一.Spring Security簡介

Spring Security是一個能夠爲基於Spring的企業應用系統提供聲明式的安全訪問控制解決方案的安全框架。它提供了一組可以在Spring應用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反轉Inversion of Control ,DI:Dependency Injection 依賴注入)和AOP(面向切面編程)功能,爲應用系統提供聲明式的安全訪問控制功能,減少了爲企業系統安全控制編寫大量重複代碼的工作。

二.Spring Security的使用步驟(固定用戶名和密碼)

1.在maven中引入spring security座標
<!-- 引入springSecrity依賴 -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>4.1.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>4.1.0.RELEASE</version>
</dependency>
2.在web.xml中配置spring security攔截器

注意事項 : 過濾器的名稱是固定的,不可改變,否則spring找不到

<!-- 配置spring Security -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/spring-security.xml</param-value>
     </context-param>
     <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
     </listener>

    <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>
3.在spring配置中配置
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="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.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

    <!-- 配置放行路徑 -->
    <http pattern="/*.html" security="none"></http><!-- login.html在根目錄下 -->
    <http pattern="/css/**" security="none"></http>
    <http pattern="/img/**" security="none"></http>
    <http pattern="/js/**" security="none"></http>
    <http pattern="/plugins/**" security="none"></http>

    <!-- 配置頁面攔截規則 -->
    <http use-expressions="false">
        <!-- 
            /**: 攔截所有?
            access : 配置角色 必須要以ROLE_開頭
         -->
        <intercept-url pattern="/**" access="ROLE_ADMIN"/>
        <!-- 
            開啓表單登陸功能(默認 username password) 表單action:/login
            login-page:登陸頁面
            default-target-url:登陸成功頁面
            authentication-failure-url:登陸失敗跳轉頁面
            always-use-default-target:總是跳轉到默認的成功頁面
         -->
        <form-login login-page="/login.html" default-target-url="/admin/index.html" authentication-failure-url="/login.html" always-use-default-target="true"/>
        <!-- 關閉跨站請求僞造檢測 -->
        <csrf disabled="true"/>
        <!-- 關閉對框架頁的攔截 -->
        <headers>
            <frame-options policy="SAMEORIGIN"/>
        </headers>
    </http>

    <!-- 配置安全管理器 -->
    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="admin" password="admin" authorities="ROLE_ADMIN"/>
                <user name="root" password="root" authorities="ROLE_ADMIN"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

三.Spring Security的使用步驟(從數據庫中查詢用戶名和密碼)

1.和上述不同點
步驟一:創建UserDetailsServiceImpl實現org.springframework.security.core.userdetails.UserDetailsService接口
import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.pinyougou.pojo.TbSeller;
import com.pinyougou.sellergoods.service.SellerService;

/**
 * 商家認證類
 * 
 * @author Administrator
 *
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    private SellerService sellerService;

    public void setSellerService(SellerService sellerService) {
        this.sellerService = sellerService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根據用戶名查詢用戶
        TbSeller tbSeller = sellerService.findOne(username);
        // 查詢到,判斷狀態是否審覈通過
        if (tbSeller != null) {
            // 審覈通過,返會結果(0:正在審覈,1:已審覈,2:審覈未通過,3:關閉)
            if ("1".equals(tbSeller.getStatus())) {
                List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
                authorities.add(new SimpleGrantedAuthority("ROLE_SELLER"));
                return new User(username, tbSeller.getPassword(), authorities);
            } else {
                // 審覈未通過
                return null;
            }
        } else {
            // 沒有查詢到,返回null
            return null;
        }

    }

}
步驟二:配置spring security的配置文件

遇到問題:因爲在UserDetailsServiceImpl類中注入了SellerService,但是SellerService是使用dubbo遠程調用的
解決: 需要注入SellerService的話需要配置

    <!-- 引用dubbo 服務 --> 
    <dubbo:application name="pinyougou-shop-web" />
    <dubbo:registry address="zookeeper://192.168.25.128:2181"/>
    <dubbo:reference id="sellerService" interface="com.pinyougou.sellergoods.service.SellerService"/>

Spring Security配置文件 :

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" 
    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.xsd
                        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

    <!-- 配置放行路徑 -->
    <http pattern="/*.html" security="none"></http><!-- login.html在根目錄下 -->
    <http pattern="/css/**" security="none"></http>
    <http pattern="/img/**" security="none"></http>
    <http pattern="/js/**" security="none"></http>
    <http pattern="/plugins/**" security="none"></http>
    <!-- 放行商家入駐 -->
    <http pattern="/seller/add.do" security="none"></http>

    <!-- 配置頁面攔截規則 -->
    <http use-expressions="false">
        <intercept-url pattern="/**" access="ROLE_SELLER"/>
        <form-login login-page="/shoplogin.html" default-target-url="/admin/index.html" authentication-failure-url="/shoplogin.html" always-use-default-target="true"/>
        <!-- 關閉跨站請求僞造檢測 -->
        <csrf disabled="true"/>
        <!-- 關閉對框架頁的攔截 -->
        <headers>
            <frame-options policy="SAMEORIGIN"/>
        </headers>
        <!-- 開啓用戶退出 默認訪問地址: /logout -->
        <logout/>
    </http>

    <!-- 配置安全管理器 -->
    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService">
        </authentication-provider>
    </authentication-manager>

    <!-- 配置認證類 -->
    <beans:bean id="userDetailsService" class="com.pinyougou.shop.service.UserDetailsServiceImpl">
        <beans:property name="sellerService" ref="sellerService"/>
    </beans:bean>

    <!-- 引用dubbo 服務 --> 
    <dubbo:application name="pinyougou-shop-web" />
    <dubbo:registry address="zookeeper://192.168.25.128:2181"/>
    <dubbo:reference id="sellerService" interface="com.pinyougou.sellergoods.service.SellerService"/>
</beans:beans>

其他配置大同小異,參考Spring Security的第一種使用方式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章