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);
// 得到當(dāng)前執(zhí)行的用戶
Subject currentUser = SecurityUtils.getSubject();
// 創(chuàng)建token令牌,用戶名/密碼
UsernamePasswordToken token = new UsernamePasswordToken("zb", "1");
try {
// 身份認(rèn)證
currentUser.login(token);
System.out.println("身份認(rèn)證成功!" + token.getUsername());
} catch (IncorrectCredentialsException e) {
System.out.println("登錄密碼錯誤");
} catch (ExcessiveAttemptsException e) {
System.out.println("登錄失敗次數(shù)過多");
} 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();
數(shù)據(jù)庫的表必須是user
字段為:
userName和passWord