JdbcRealm.ini:
[main]
#数据源选择的是c3p0
dataSource=com.mchange.v2.c3p0.ComboPooledDataSource
dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://localhost:3306/db_shiro
dataSource.user=root
dataSource.password=123456
#定义一个jdbc的realm,取名为jdbcRealm
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
#jdbcRealm中有个属性是dataSource,选择我们上边定义的dataSource
jdbcRealm.dataSource=$dataSource
#SecurityManager中的realm选择上面定义的jdbcRealm
securityManager.realms=$jdbcRealm
后台代码:
package cn.mxr;
import org.apache.shiro.util.Factory;
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;
public class JdbcRealm {
public static void main(String[] args) {
// 读取配置文件,初始化SecurityManager工厂
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:jdbcRealm.ini");
System.out.println(444);
// 获取securityManager实例
SecurityManager securityManager = factory.getInstance();
System.out.println(333);
// 把securityManager实例绑定到SecurityUtils
SecurityUtils.setSecurityManager(securityManager);
System.out.println(222);
// 得到当前执行的用户
Subject currentUser = SecurityUtils.getSubject();
System.out.println(111);
// 创建token令牌,用户名/密码
UsernamePasswordToken token = new UsernamePasswordToken("2", "222");
System.out.println(555);
try{
System.out.println("token:"+token);
// 身份认证
currentUser.login(token);
System.out.println("身份认证成功!");
}catch(AuthenticationException e){
e.printStackTrace();
System.out.println("身份认证失败!");
}
System.out.println(666);
// 退出
currentUser.logout();
}
}
报错:Establishing SSL connection without server’s identity verification is not recommended
解决方案:
dataSource.jdbcUrl=jdbc:mysql://localhost:3306/db_shiro后加?useSSL=false
dataSource.jdbcUrl=jdbc:mysql://localhost:3307/db_shiro?useSSL=false
然后又报错:Unknown system variable 'query_cache_size'
问题:版本过低因为数据库是8.0.15所以改成8.0.15
接着又报错:The server time zone value '???ú±ê×??±??' is .............
原因:时间总是有问题,比实际时间要早8小时。
解决方式:在jdbc连接的url后面加上serverTimezone=GMT即可解决问题,如果需要使用gmt+8时区,需要写成GMT%2B8
最后代码:
[main]
#数据源选择的是c3p0
dataSource=com.mchange.v2.c3p0.ComboPooledDataSource
dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://localhost:3306/db_shiro?useSSL=false&serverTimezone=GMT
dataSource.user=root
dataSource.password=123456
#定义一个jdbc的realm,取名为jdbcRealm
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
#jdbcRealm中有个属性是dataSource,选择我们上边定义的dataSource
jdbcRealm.dataSource=$dataSource
#SecurityManager中的realm选择上面定义的jdbcRealm
securityManager.realms=$jdbcRealm