Spring Security安全框架入門篇(轉載)

轉載:https://blog.csdn.net/u013142781/article/details/50631663

一、Spring Security相關概念

1.1.、Spring Security介紹:

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

1.2、Spring Security實現原理:

Spring Security對Web安全性的支持大量地依賴於Servlet過濾器。通過這些過濾器攔截進入請求,判斷是否已經登錄認證且具訪問對應請求的權限。

要完成訪問控制,Spring Security至少需要下面四個攔截器(調度器、認證管理器、權限資源關聯器、訪問決策器)進行配合完成:

<!-- mySecurityInterceptor這裏我們把它命名爲調度器吧 -->
<!-- 必須包含 authenticationManager,securityMetadataSource,accessDecisionManager 三個屬性 -->   
<!-- 我們的所有控制將在這三個類中實現 --> 
<!-- 它繼承AbstractSecurityInterceptor類並實現了Filter接口 --> 
<bean id="mySecurityInterceptor" class="com.luo.Filter.MySecurityInterceptor">  
    <b:property name="authenticationManager" ref="authenticationManager" />  
    <b:property name="securityMetadataSource" ref="securityMetadataSource" />  
    <b:property name="accessDecisionManager" ref="accessDecisionManager" />  

</bean>  

<!-- 認證管理器,實現用戶認證的入口 -->  
<authentication-manager alias="authenticationManager">  
    <authentication-provider user-service-ref="myUserDetailService" />   
</authentication-manager>  

<!-- 在這個類中,你就可以從數據庫中讀入用戶的密碼,角色信息等 -->  
<!-- 主要實現UserDetailsService接口即可,然後返回用戶數據 -->  
<bean id="myUserDetailService" class="com.luo.Filter.MyUserDetailService" />  

<!-- 權限資源關聯器,將所有的資源和權限對應關係建立起來,即定義某一資源可以被哪些角色訪問 -->  
<!-- 它實現了FilterInvocationSecurityMetadataSource接口 -->  
<bean id="securityMetadataSource" class="com.luo.Filter.MyFilterInvocationSecurityMetadataSource" /> 

<!--訪問決策器,決定某個用戶具有的角色,是否有足夠的權限去訪問某個資源 --> 
<!-- 它實現了AccessDecisionManager接口 --> 
<bean id="accessDecisionManager" class="com.luo.Filter.MyAccessDecisionManager">
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

看完上面的配置,可能未必能夠完全明白,下面我們再進一步說明。

(1)首先我們自定義一個過濾器(調度器,這裏我們命名爲mySecurityInterceptor),這個過濾器繼承AbstractSecurityInterceptor類(這裏先說明,本文但凡不是自定義的類或接口都是Spring Security提供的,無須深究)。 它至少包含 authenticationManager,accessDecisionManager,securityMetadataSource三個屬性,我們的所有控制將在這三個類中實現。

(2)登錄驗證:自定義類MyUserDetailService實現UserDetailsService接口和其loadUserByUsername方法,這個方法根據用戶輸入的用戶名,從數據庫裏面獲取該用戶的所有權限細信息(統稱用戶信息)。Spring Security的AuthenticationProcessingFilter攔截器調用authenticationManager,類MyUserDetailService拿到用戶信息後,authenticationManager對比用戶的密碼(即驗證用戶),如果通過了,那麼相當於通過了AuthenticationProcessingFilter攔截器,也就是登錄驗證通過。

(3)資源訪問控制:MySecurityInterceptor繼承AbstractSecurityInterceptor、實現Filter是必須的。登陸後,每次訪問資源都會被MySecurityInterceptor這個攔截器攔截,它首先會調用MyFilterInvocationSecurityMetadataSource類的getAttributes方法獲取被攔截url所需的權限,在調用MyAccessDecisionManager類decide方法判斷用戶是否夠權限。

可能文字描述還是比較抽象,通過實例應該能讓大家更加清楚其原理。


補充說明一下:

UserDetailsService在身份認證中的作用:

Spring Security中進行身份驗證的是AuthenticationManager接口,ProviderManager是它的一個默認實現,但它並不用來處理身份認證,而是委託給配置好的AuthenticationProvider,每個AuthenticationProvider會輪流檢查身份認證。檢查後或者返回Authentication對象或者拋出異常。

驗證身份就是加載響應的UserDetails,看看是否和用戶輸入的賬號、密碼、權限等信息匹配。此步驟由實現AuthenticationProvider的DaoAuthenticationProvider(它利用UserDetailsService驗證用戶名、密碼和授權)處理。

因此,登錄認證其實可以不實現UserDetailsService,而是實現AuthenticationProvider,然後在AuthenticationProvider裏面獲取用戶輸入的用戶名和密碼進行校驗也是可以的。或者兩者一起使用。

下面推薦兩者一起使用的方式http://blog.sina.com.cn/s/blog_4adc4b090102uy2f.html

另外,只實現AuthenticationProvider而不實現UserDetailsService的方式,這類是重寫AuthenticationProvider的authenticate方法的代碼:

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String inputLoginId = authentication.getName();   //獲取用戶輸入的用戶名
    String inputPasswd = authentication.getCredentials().toString(); /獲取用戶輸入的密碼

    LOGGER.info("用戶{}登錄", inputLoginId);
    try{
        // 查詢此用戶信息
        myUser myUser = null;  //根據用戶名到數據庫裏面查詢用戶數據
        if (myUser == null ) {
            throw new Exception("您輸入的賬號不存在");
        }
        if (myUser.getUserStatus() == UserStatus.locked) {
            throw new Exception("您的賬號已被鎖定");
        }

        String encodedPassword = myUser.getLoginPasswd();
        // 校驗密碼是否正確
        boolean authenticated = verifyPassword(inputPasswd, encodedPassword);
        if (authenticated) {
            // 認證成功處理
            updateLoginInfo(myUser.getLoginId(), 0, null);
        } else {
            // 認證失敗處理
            authenticateErrorProcess(portalUser);
        }

        List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
        for (MyRole myRole : myUser.allRoleList()) {
            grantedAuths.add(new SimpleGrantedAuthority(myRole.getRoleCode()));
        }
        MyAuthUser authUser = new PortalAuthUser(inputLoginId, inputPasswd, true, true, true, true, grantedAuths);
        authUser.setPortalUser(portalUser);
        return new UsernamePasswordAuthenticationToken(authUser, null, authUser.getAuthorities());
    }catch(Exception e){
        LOGGER.warn("用戶登錄失敗", e);
        throw new Exception(" 請確認用戶名或者密碼是否正確);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

二、Spring Security實例詳細說明

本實例環境:eclipse + maven
本實例採用的主要技術:spring + springmvc + spring security

時間有限這裏只對其訪問控制原理進行了闡述,例子後面再補上,不過關於實例推薦參考博文:http://blog.csdn.net/u012367513/article/details/38866465,這篇文章寫得非常詳細!!!

這是春節前最後一篇博客了,過年回來還有另外的學習計劃,可能這個例子的TODO有點遙遙無期啊……..哈哈

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