1. 程式人生 > >八、AuthenticationStrategy(身份驗證策略)

八、AuthenticationStrategy(身份驗證策略)

AuthenticationStrategy(身份驗證策略)

AuthenticationStrategy 是個無狀態的元件,在認證過程中會進行4次呼叫。
① 在所有Realm被呼叫之前
②在呼叫Realm的getAuthenticationInfo方法之前
③在呼叫Realm的getAuthenticationInfo 方法之後
④在所有Realm被呼叫之後

ModularRealmAuthenticator
org.apache.shiro.authc.pam.ModularRealmAuthenticator

在這裡插入圖片描述

AuthenticationStrategy
org.apache.shiro.authc.pam.AuthenticationStrategy

在這裡插入圖片描述

Shiro有3中認證策略的具體實現 AuthenticationStrategy類:
AtLeastOneSuccessfulStrategy(預設)
只要一個或者多個Realm認證通過,則整體身份認證就會視為成功。
FirstSuccessfulStrategy
只有第一個驗證通過,才會視為整體認證通過。其他的會被忽略。
AllSuccessfulStrategy
只有所有的Realm認證成功,才會被視為認證通過
自定義策略:繼承org.apache.shiro.authc.pam.AbstractAuthenticationStrategy。

  • Realm順序對認證是有影響的。

spring-shiro.xml 配置 認證策略:


<!-- Shiro預設會使用Servlet容器的Session,可通過sessionMode屬性來指定使用Shiro原生Session -->
<!-- 這裡主要是設定自定義的單Realm應用,若有多個Realm,可使用'realms'屬性代替 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <property name="cacheManager" ref="cacheManager"/>
     <!--<property name="realm" ref="myRealm"/>-->
     
    <property name="authenticator" ref="authenticator"/>
</bean>

<!--多個realm 配置-->
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
    <!--配置認證策略-->
    <property name="authenticationStrategy" ref="allSuccessfulStrategy"/>
    <property name="realms">
        <list>
            <ref bean="firstRealm"/>
            <ref bean="secondRealm"/>
        </list>
    </property>
</bean>
<!--全部通過-->
<bean id="allSuccessfulStrategy" class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"/>
<!--只有第一個驗證通過,才會視為整體認證通過。其他的會被忽略。-->
<bean id="firstSuccessfulStrategy" class="org.apache.shiro.authc.pam.FirstSuccessfulStrategy"/>
<!--預設-->
<bean id="atLeastOneSuccessfulStrategy" class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"/>