jdbc_realm.ini:
[main]
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
dataSource=com.mchange.v2.c3p0.ComboPooledDataSource
dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://localhost:3306/shiro_db
dataSource.user=root
dataSource.password=root
jdbcRealm.dataSource=$dataSource
securityManager.realms=$jdbcRealm
// 读取配置文件,初始化SecurityManager工厂
Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory(
"classpath:jdbc_realm.ini");
// 获取securityManager实例
org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
// 把securityManager实例绑定到SecurityUtils
SecurityUtils.setSecurityManager(securityManager);
// 得到当前执行的用户
Subject currentUser = SecurityUtils.getSubject();
// 创建token令牌,用户名/密码
UsernamePasswordToken token = new UsernamePasswordToken("zb", "1");
try {
// 身份认证
currentUser.login(token);
System.out.println("身份认证成功!" + token.getUsername());
} catch (IncorrectCredentialsException e) {
System.out.println("登录密码错误");
} catch (ExcessiveAttemptsException e) {
System.out.println("登录失败次数过多");
} catch (LockedAccountException e) {
System.out.println("帐号已被锁定");
} catch (DisabledAccountException e) {
System.out.println("帐号已被禁用");
} catch (ExpiredCredentialsException e) {
System.out.println("帐号已过期");
} catch (UnknownAccountException e) {
System.out.println("帐号不存在");
}
// 退出
currentUser.logout();
数据库的表必须是user
字段为:
userName和passWord