spring安全框架:spring-security

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

(1) 相關依賴html

        <!-- spring安全框架 -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>

(2) spring-security.xml配置文件前端

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
    xmlns:context="http://www.springframework.org/schema/context"
    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://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
    
    <context:property-placeholder location="classpath:properties/*.properties" />
    
    <!-- 如下頁面不被攔截 -->
    <http pattern="/*.html" security="none"></http>
    <http pattern="/seller/add.do" security="none"></http><!-- 放行註冊請求 -->
    <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">
        <!-- 
            use-expressions="false":是否使用spel表達式
            pattern="/*":攔截根目錄;pattern="/**":攔截根目錄及子目錄
            login-page="/login.html":登陸頁
            default-target-url="/admin/index.html":登錄成功跳轉
            authentication-failure-url="/login.html":登錄失敗跳轉
            always-use-default-target="true":
         -->
        <intercept-url pattern="/**" access="ROLE_SELLER" />
        <!-- spring security登錄 -->
        <form-login login-page="/shoplogin.html" default-target-url="/admin/index.html"
            authentication-failure-url="/shoplogin.html" always-use-default-target="true" />
        <!-- spring security登出 -->
        <logout logout-url="/loginout" logout-success-url="/shoplogin.html"/>
        <!-- 防止跨站請求僞造(jsp頁面),項目是html,因此能夠設置關閉 -->
        <csrf disabled="true" />
        <!-- spring security默認攔截框架頁(iframe等) -->
        <headers>
            <frame-options policy="SAMEORIGIN" />
        </headers>
    </http>

    <!-- 認證管理器 -->
    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService">
            <!-- 配置加密/解密算法 -->
            <password-encoder ref="passwordEncoder"></password-encoder>
        </authentication-provider>
    </authentication-manager>
    
    <!-- 配置認證類 -->
    <beans:bean id="userDetailsService" class="com.xxx.sellergoods.service.impl.UserDetailsServiceImpl">
        <beans:property name="sellerService" ref="sellerService"></beans:property>
    </beans:bean>
    
    <!-- 引用dubbo 服務 -->
    <!-- 引用信息使用方,用於計算依賴關係 -->
    <dubbo:application name="xxx-sellergoods-web" />
    <!-- zookeeper註冊中心 -->
    <dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"></dubbo:registry>
    <!-- 獲取遠程服務實例到本地 -->
    <dubbo:reference id="sellerService" interface="com.xxx.sellergoods.service.SellerService"></dubbo:reference>
    
    <!-- 配置加密/解密算法bean -->
    <beans:bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></beans:bean>
</beans:beans>

(3) web.xmljava

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <display-name>xxx-sellergoods-web</display-name>
    <welcome-file-list>
        <welcome-file>shoplogin.html</welcome-file>
    </welcome-file-list>

    <!-- post亂碼過濾器 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 前端控制器 -->
    <servlet>
        <servlet-name>xxx-sellergoods-web</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- contextConfigLocation不是必須的, 若是不配置contextConfigLocation,
        springmvc的配置文件默認在:WEB-INF/servlet的name+"-servlet.xml" --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>xxx-sellergoods-web</servlet-name> <!-- 攔截全部請求jsp除外 --> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 加載spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- spring安全框架 --> <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> </web-app>

(4) 認證類web

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;
public class UserDetailsServiceImpl implements UserDetailsService {

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

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        
        List<GrantedAuthority> grantAuths = new ArrayList<>();
        grantAuths.add(new SimpleGrantedAuthority("ROLE_SELLER"));
        /**
         * User:
         * * 參數:
         *     * 1.用戶名
         *  * 2.密碼
         *  * 3.認證信息(角色)
         */
        // 去數據庫進行查詢:
        TbSeller seller = sellerService.findByUserName(username);
        if(seller != null){
            if(seller.getStatus().equals("1")){
                return new User(username,seller.getPassword(),grantAuths );
            }else{
                return null;
            }
        }
        return null; 
    }
}
相關文章
相關標籤/搜索