疑惑: 程序是經過什麼方法匹配到數據庫中相應的用戶名及密碼的?java
(1)這是配置文件,其中並未說起用戶名和密碼的匹配方法:mysql
[main] jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm dataSource=com.alibaba.druid.pool.DruidDataSource dataSource.driverClassName=com.mysql.jdbc.Driver dataSource.url=jdbc:mysql://localhost:3306/test dataSource.username=jack dataSource.password=123 jdbcRealm.dataSource=$dataSource securityManager.realms=$jdbcRealm
(2)這是程序,其中也沒有用戶名和密碼的匹配方法:sql
package com.shiro.hello; 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; public class JdbcRealmTest { public static void main(String[] args) { // 讀取配置文件,初始化SecurityManager工廠 Factory<SecurityManager> factory = new IniSecurityManagerFactory( "classpath:jdbc_realm.ini"); // 獲取securityManager實例 SecurityManager securityManager = factory.getInstance(); // 把securityManager實例綁定到SecurityUtils SecurityUtils.setSecurityManager(securityManager); // 獲得當前執行的用戶 Subject currentUser = SecurityUtils.getSubject(); // 建立token令牌,用戶名/密碼 UsernamePasswordToken token = new UsernamePasswordToken("java1234", "1234567"); try { // 身份認證 currentUser.login(token); System.out.println("身份認證成功!"); } catch (AuthenticationException e) { e.printStackTrace(); System.out.println("身份認證失敗!"); } // 退出 currentUser.logout(); } }
(3)這是數據庫字段:數據庫
解決辦法: 經過羣裏發文獲得了大神的指點,這裏的表和字段是能夠自定義的,只須要在ini配置文件中進行相應的配置便可。apache
[main] jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm dataSource=com.alibaba.druid.pool.DruidDataSource dataSource.driverClassName=com.mysql.jdbc.Driver dataSource.url=jdbc:mysql://localhost:3306/test dataSource.username=jack dataSource.password=123 jdbcRealm.authenticationQuery=select password from users where username = ? jdbcRealm.dataSource=$dataSource securityManager.realms=$jdbcRealm
注意這個配置文件多了一句ui
jdbcRealm.authenticationQuery=select password from users where username = ?
後面的sql語句就能夠自定義。好比想把表名換成hellourl
jdbcRealm.authenticationQuery=select password from hello where username = ?
換過以後,程序就會在數據庫中hello表中進行查找驗證了。spa