2.1、數(shù)據(jù)庫設(shè)計
在實際開發(fā)中荒吏,用戶名密碼、角色渊鞋、權(quán)限需要存在數(shù)據(jù)庫中動態(tài)管理绰更。一個簡單的Shiro+MySQL的項目需要三張表瞧挤,表結(jié)構(gòu)及初始化數(shù)據(jù)如下:
shiro_user表:
DROP TABLE IF EXISTS `shiro_user`;
CREATE TABLE `shiro_user` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`USER_NAME` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
`PASSWORD` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
PRIMARY KEY (`ID`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
INSERT INTO `shiro_user` VALUES (1, 'test', '123456');
shiro_user_role表:
DROP TABLE IF EXISTS `shiro_user_role`;
CREATE TABLE `shiro_user_role` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`USER_NAME` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
`ROLE_NAME` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
PRIMARY KEY (`ID`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
INSERT INTO `shiro_user_role` VALUES (1, 'test', 'role1');
shiro_role_permission表:
DROP TABLE IF EXISTS `shiro_role_permission`;
CREATE TABLE `shiro_role_permission` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`ROLE_NAME` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
`PERM_NAME` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
PRIMARY KEY (`ID`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
INSERT INTO `shiro_role_permission` VALUES (1, 'role1', 'perm1');
2.2、添加依賴
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
2.3儡湾、配置文件
在resources文件夾下新建一個shiro.ini內(nèi)容如下:
[main]
dataSource=org.springframework.jdbc.datasource.DriverManagerDataSource
#
dataSource.driverClassName=com.mysql.jdbc.Driver
# user:數(shù)據(jù)庫名
dataSource.url=jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
# 用戶名
dataSource.username=root
#如果數(shù)據(jù)庫沒有密碼特恬,就不要寫這行
dataSource.password=123456
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
#是否檢查權(quán)限
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.dataSource=$dataSource
#重寫sql語句
#根據(jù)用戶名查詢出密碼
jdbcRealm.authenticationQuery = select password from shiro_user where user_name = ?
#根據(jù)用戶名查詢出角色
jdbcRealm.userRolesQuery = select role_name from shiro_user_role where user_name = ?
#根據(jù)角色名查詢出權(quán)限
jdbcRealm.permissionsQuery = select perm_name from shiro_role_permission where role_name = ?
securityManager.realms=$jdbcRealm
2.4、測試代碼
跟上一篇的一樣徐钠,看過的可以跳過
public class ShiroTest {
private static final transient Logger log =
LoggerFactory.getLogger(ShiroTest.class);
public static void main(String[] args){
//1癌刽、SecurityManager:classpath:shiro.ini
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//2、解析配置文件尝丐,并返回一些SecurityManager
SecurityManager securityManager = factory.getInstance();
//3显拜、SecurityManager綁定給SecurityUtils
SecurityUtils.setSecurityManager(securityManager);
//4、安全操作爹袁,Subject是當前登錄的用戶
Subject currentUser = SecurityUtils.getSubject();
//5远荠、測試在應(yīng)用的當前回話中設(shè)置屬性
Session session = currentUser.getSession();
//如果用戶沒有登陸過
if(!currentUser.isAuthenticated()){
UsernamePasswordToken token = new UsernamePasswordToken("test","123456");
//記住我
token.setRememberMe(true);
try{
currentUser.login(token);
log.info("用戶【"+currentUser.getPrincipal()+"】 登錄成功");
//登錄之后查看是否擁有指定角色
if(currentUser.hasRole("admin")){
log.info("有admin角色");
}else{
log.info("沒有admin角色");
}
if(currentUser.hasRole("role1")){
log.info("有role1角色");
}else{
log.info("沒有role1角色");
}
//查看用戶是否擁有某個權(quán)限
if(currentUser.isPermitted("perm1")){
log.info("有perm1權(quán)限");
}else{
log.info("沒有perm1權(quán)限");
}
if(currentUser.isPermitted("guest")){
log.info("有g(shù)uest權(quán)限");
}else{
log.info("沒有g(shù)uest權(quán)限");
}
//登出
currentUser.logout();
}catch (UnknownAccountException uae){
log.info(token.getPrincipal()+" 賬戶不存在");
}catch (IncorrectCredentialsException ice){
log.info(token.getPrincipal()+" 密碼不正確");
}catch (LockedAccountException lae){
log.info(token.getPrincipal()+" 用戶被鎖定了 ");
}catch (AuthenticationException ae){
//無法判斷是什么錯
log.info(ae.getMessage());
}
}
}
}