天天看點

shiro——認證Authentication

目錄

1. 類圖

2、ModularRealmAuthenticator 類

1. 類圖

Authenticator是認證的入口。

shiro——認證Authentication

2、ModularRealmAuthenticator 類

這是一個shiro自帶的類,實作了Authenticator接口,作用是友善我們配置多個Realm。

假設定義Realm1 、Realm2、 Realm3 是三個實作了Realm接口的類。

首先ini配置檔案(下面的配置是屬于[main]的,這裡隻展示有關的):

modularRealmAuthenticator=org.apache.shiro.authc.pam.ModularRealmAuthenticator
securityManager.authenticator=$modularRealmAuthenticator
atLeastOneSuccessfulStrategy=org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy
securityManager.authenticator.authenticationStrategy=$atLeastOneSuccessfulStrategy
securityManager.realms=$realm1,$realm2,$realm3
           

認證政策:

FirstSuccessfulStrategy:隻要有一個Realm驗證成功即可,隻傳回第一個Realm身份驗證成功的認證資訊,其他的忽略;

AtLeastOneSuccessfulStrategy:隻要有一個Realm驗證成功即可,和FirstSuccessfulStrategy不同,傳回所有Realm身份驗證成功的認證資訊;

AllSuccessfulStrategy:所有Realm驗證成功才算成功,且傳回所有Realm身份驗證成功的認證資訊,如果有一個失敗就失了。

測試代碼(login成功後,可以調用subject的getPrincipal() 和 getPrincipals() 擷取認證成功資訊):

Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
/*建立token,傳入登入的使用者和密碼*/
UsernamePasswordToken token = new UsernamePasswordToken("alice", "123456");
subject.isAuthenticated();
/*進行登入認證*/
subject.login(token);
           

自定義政策:繼承org.apache.shiro.authc.pam.AbstractAuthenticationStrategy 這個抽象類,然後實作你自定義的政策。

在看看認證使用的是什麼? 預設用的是ModularRealmAuthenticator類,是以無需設定SecurityManager的authenticator:

shiro——認證Authentication

注意:SecurityManager的authenticator無需配置,預設就使用的ModularRealmAuthenticator。

繼續閱讀