昨天講了shiro的認證流程以及代碼實現,今天將對這個進行擴展。 因為我們的測試數據是shiro.ini文件中配置的靜態數據,但實際上數據應該從資料庫中查詢出來才合理,因此我們今天講講JdbcRealm的使用。 本次需要的jar包如下: commons-beanutils-1.9.3.jarcomm ...
昨天講了shiro的認證流程以及代碼實現,今天將對這個進行擴展。
因為我們的測試數據是shiro.ini文件中配置的靜態數據,但實際上數據應該從資料庫中查詢出來才合理,因此我們今天講講JdbcRealm的使用。
本次需要的jar包如下:
commons-beanutils-1.9.3.jar
commons-logging-1.2.jar
jcl-over-slf4j-1.7.12.jar
log4j-1.2.16.jar
shiro-all-1.4.1.jar
slf4j-api-1.7.25.jar
slf4j-log4j12-1.6.4.jar
mysql-connector-java-5.1.47.jar
mchange-commons-java-0.2.11.jar
c3p0-0.9.5.2.jar
IniSecurityManagerFactory部分源碼:
public static final String MAIN_SECTION_NAME = "main"; public static final String SECURITY_MANAGER_NAME = "securityManager"; public static final String INI_REALM_NAME = "iniRealm"; ...... protected Map<String, ?> createDefaults(Ini ini, Ini.Section mainSection) { Map<String, Object> defaults = new LinkedHashMap<String, Object>(); SecurityManager securityManager = createDefaultInstance(); defaults.put(SECURITY_MANAGER_NAME, securityManager); if (shouldImplicitlyCreateRealm(ini)) { Realm realm = createRealm(ini); if (realm != null) { defaults.put(INI_REALM_NAME, realm); } } ......
從這段源碼可以看到,IniSecurityManagerFactory在初始化時預設將iniRealm設置到SecurityManager中,除非我們自己設置SecurityManager使用哪個realm,它獲取判斷realm不為空,才將我們設置的realm設置到SecurityManager中,因此我們要在shiro.ini中配置新的realm即JdbcRealm。
JdbcRealm部分源碼:
/** * The default query used to retrieve account data for the user. */ protected static final String DEFAULT_AUTHENTICATION_QUERY = "select password from users where username = ?"; /** * The default query used to retrieve account data for the user when {@link #saltStyle} is COLUMN. */ protected static final String DEFAULT_SALTED_AUTHENTICATION_QUERY = "select password, password_salt from users where username = ?"; /** * The default query used to retrieve the roles that apply to a user. */ protected static final String DEFAULT_USER_ROLES_QUERY = "select role_name from user_roles where username = ?"; /** * The default query used to retrieve permissions that apply to a particular role. */ protected static final String DEFAULT_PERMISSIONS_QUERY = "select permission from roles_permissions where role_name = ?"; ...... public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } ...... protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); // Null username is invalid if (username == null) { throw new AccountException("Null usernames are not allowed by this realm."); } Connection conn = null; SimpleAuthenticationInfo info = null; try { conn = dataSource.getConnection(); String password = null; String salt = null; switch (saltStyle) { case NO_SALT: password = getPasswordForUser(conn, username)[0]; break; case CRYPT: // TODO: separate password and hash from getPasswordForUser[0] throw new ConfigurationException("Not implemented yet"); //break; case COLUMN: String[] queryResults = getPasswordForUser(conn, username); password = queryResults[0]; salt = queryResults[1]; break; case EXTERNAL: password = getPasswordForUser(conn, username)[0]; salt = getSaltForUser(username); } if (password == null) { throw new UnknownAccountException("No account found for user [" + username + "]"); } info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName()); if (salt != null) { info.setCredentialsSalt(ByteSource.Util.bytes(salt)); } } catch (SQLException e) { final String message = "There was a SQL error while authenticating user [" + username + "]"; if (log.isErrorEnabled()) { log.error(message, e); } // Rethrow any SQL errors as an authentication exception throw new AuthenticationException(message, e); } finally { JdbcUtils.closeConnection(conn); } return info; }
從JdbcRealm的源碼中我們看到了許多sql語句,都是從表users中去查詢欄位username、password、password_salt等等,而且源碼中還出現了dataSource,而這個dataSource是需要我們set進去的,因此要使用JdbcRealm,我們必須在資料庫創建表users以及對應的欄位,還需要為JdbcRealm註入dataSource。下麵我們開始配置shiro.ini文件。
shiro.ini文件:
[main] dataSource=com.mchange.v2.c3p0.ComboPooledDataSource dataSource.driverClass=com.mysql.jdbc.Driver dataSource.jdbcUrl=jdbc:mysql://localhost:3306/test dataSource.user=root dataSource.password=root myRealm=org.apache.shiro.realm.jdbc.JdbcRealm myRealm.dataSource=$dataSource securityManager.realm=$myRealm
差點忘了說,在shiro.ini文件中,有許多模塊組成,比如昨天的[users]用來存放靜態數據,和上面的[main]是用來配置SecurityManager和它所需要的依賴組件如realm的模塊,當然還有配置用戶角色的模塊[role],我們這裡就不多講了,留到授權模塊再將。
瞭解了[main]的應用,我們再看看上面的配置,首先我們配置了一個dataSource(這裡配的是數據源c3p0,記得導包哦),包括配置它的資料庫驅動、Url、資料庫登錄名以及密碼,然後配了一個myRealm指向了JdbcRealm,再將上面的dataSource設置到myRealm中從而實現了dataSource的註入(這裡的$代表註入,跟spring的註入異曲同工),再將這個myRealm設置成SecurityManager的預設realm從而完成配置。
配置完成了,接下來我們還要在資料庫中創建users表:
如圖,在test資料庫下創建users表,其中必須包含JdbcRealm類中的sql語句中出現的欄位,這裡我們設置了三個。
創建完表,我們開始編碼,流程其實跟第一天的差不多:
package test_JdbcRealm; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestJdbcRealm { private static final Logger logger = LoggerFactory.getLogger(TestJdbcRealm.class); public static void main(String[] args) { //1.創建securityManager工廠 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); //2.獲取securityManager實例 SecurityManager securityManager = factory.getInstance(); //3.將SecurityManager實例設置到SecurityUtils工具類中 SecurityUtils.setSecurityManager(securityManager); //4。創建Subject實例 Subject subject = SecurityUtils.getSubject(); //5.獲取token,模擬用戶登陸 UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123456"); try { //6.認證token subject.login(token); if(subject.isAuthenticated()) { logger.info("登陸成功"); } } catch (AuthenticationException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.error("用戶名或密碼錯誤,登陸失敗"); } } }
2019-07-25 23:30:43,705 INFO [com.mchange.v2.log.MLog] - MLog clients using slf4j logging. 2019-07-25 23:30:44,102 INFO [com.mchange.v2.c3p0.C3P0Registry] - Initializing c3p0-0.9.5.2 [built 08-December-2015 22:06:04 -0800; debug? true; trace: 10] 2019-07-25 23:30:44,211 INFO [org.apache.shiro.config.IniSecurityManagerFactory] - Realms have been explicitly set on the SecurityManager instance - auto-setting of realms will not occur. 2019-07-25 23:30:44,233 INFO [com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource] - Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, contextClassLoaderSource -> caller, dataSourceName -> 2zm2h8a4bl36b813yacsm|7e0ea639, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, extensions -> {}, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, forceUseNamedDriverClass -> false, identityToken -> 2zm2h8a4bl36b813yacsm|7e0ea639, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/test, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, preferredTestQuery -> null, privilegeSpawnedThreads -> false, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ] 2019-07-25 23:30:44,525 INFO [org.apache.shiro.session.mgt.AbstractValidatingSessionManager] - Enabling session validation scheduler... 2019-07-25 23:30:44,537 INFO [test_JdbcRealm.TestJdbcRealm] - 登陸成功
同樣是這幾個步驟,但是在載入配置文件生成SecurityManager的實例卻是不一樣的,因為我們在配置文件中配置了SecurityManager的預設realm為JdbcRealm,因此在subjec.login(token)認證時,最終會通過JdbcRealm的認證方法從資料庫中查出用戶數據來進行比對認證!
總結:
1.在使用一個類的時候,我們需要通過源碼去瞭解它需要什麼,然後才能有目的地進行配置,就像JdbcRealm這個類,它需要一張表和數據源來實現從資料庫查詢出數據進行認證;
2.shiro.ini包含多個組成部分,如[main],[users],[role]還有[url],我們需要瞭解各個部分地主要功能和作用;
3.從上面地例子我們可以得知,SecurityManager使用地realm是可以進行配置的!!因此也就說明瞭我們可以自定義realm來實現認證和授權邏輯!這部分後續我學習到了將會進行分享。
以上是我今天學習shiro所得,大家如果有什麼補充或者建議,麻煩在評論區留言,謝謝!