疑惑: 程序是经过什么方法匹配到数据库中相应的用户名及密码的?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