疑惑: 程序是通过什么方法匹配到数据库中相应的用户名及密码的?
(1)这是配置文件,其中并未提及用户名和密码的匹配方法:
[main]jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealmdataSource=com.alibaba.druid.pool.DruidDataSourcedataSource.driverClassName=com.mysql.jdbc.DriverdataSource.url=jdbc:mysql://localhost:3306/testdataSource.username=jackdataSource.password=123jdbcRealm.dataSource=$dataSourcesecurityManager.realms=$jdbcRealm
(2)这是程序,其中也没有用户名和密码的匹配方法:
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工厂 Factoryfactory = 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配置文件中进行相应的配置即可。
[main]jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealmdataSource=com.alibaba.druid.pool.DruidDataSourcedataSource.driverClassName=com.mysql.jdbc.DriverdataSource.url=jdbc:mysql://localhost:3306/testdataSource.username=jackdataSource.password=123jdbcRealm.authenticationQuery=select password from users where username = ?jdbcRealm.dataSource=$dataSourcesecurityManager.realms=$jdbcRealm
注意这个配置文件多了一句
jdbcRealm.authenticationQuery=select password from users where username = ?
后面的sql语句就可以自定义。比如想把表名换成hello
jdbcRealm.authenticationQuery=select password from hello where username = ?
换过之后,程序就会在数据库中hello表中进行查找验证了。