Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序
Shiro中有三大对象:Realm、Subject、SecuritytManager
绝大部分对于项目的说明写在代码注释中
此博客中的项目基于SpringBoot(2.6.7)整合Mybatis项目创建,其中大部分依赖版本依据SpringBoot(2.6.7)而定,小部分官方未提供版本建议需自行指定
一.导入依赖二.配置yml文件org.springframework.boot spring-boot-starter-thymeleafcom.github.theborakompanioni thymeleaf-extras-shiro2.1.0 org.springframework.boot spring-boot-starter-weborg.apache.shiro shiro-spring-boot-web-starter1.9.0 org.mybatis.spring.boot mybatis-spring-boot-starter2.2.2 mysql mysql-connector-java8.0.26 com.alibaba druid-spring-boot-starter1.1.10 log4j log4j1.2.17 org.projectlombok lombok1.18.22 org.springframework.boot spring-boot-devtools2.6.7
server:
port:
8080
mybatis:
mapper-locations: classpath:mappers
//收集页面授权信息
Map filterMap = new LinkedHashMap<>();
//权限验证 若无权限则跳转至未授权页面
//filterMap.put("/user/add","roles[user01]");//必须拥有user角色才能访问
//filterMap.put("/user/update","perms[add,update]");//必须同时拥有add与update权限才能访问
filterMap.put("/user/add","perms[add]");//必须拥有add权限才能访问
filterMap.put("/user/update","perms[update]");//必须拥有update权限才能访问
//注:数据库字段若为通配符 则代表拥有所有角色或权限
//设置页面授权
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
//设置登录页面
shiroFilterFactoryBean.setLoginUrl("/toLogin");
//设置未授权跳转页面
shiroFilterFactoryBean.setUnauthorizedUrl("/unAuthorized");
return shiroFilterFactoryBean;
}
//整合ShiroDialect 用于整合shiro与thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
数据库
资源目录结构
index.html
title
index
Login
Logout
Add
update
login.html
Title
Login
add.html(update.html、unAuthorized.html与此大同小异,不赘述)
Title
add
运行效果
访问localhost:8080进入首页,点击登录按钮进入登录页面
登录页面
登录失败提示
不同的账户拥有的权限、角色不同,看到的界面亦不同
注销后返回首页
至此,页面授权与登录认证(数据库取值)均完成


