shiro角色权限从mysql读取权限数据明明有数据判断结果无权限

Apache Shiro | Simple. Java. Security.
Learn how Shiro securely verifies identities.
Learn how Shiro handles permissions, roles and users.
Step-by-step tutorial for securing a web application with Apache Shiro.
A free InfoQ mini-book by
Apache Shiro& is a powerful and easy-to-use Java security framework that performs authentication,
authorization, cryptography, and session management. With Shiro’s easy-to-understand API, you can
quickly and easily secure any application – from the smallest mobile applications to the largest web
and enterprise applications.
Getting Started
Support logins across one or more pluggable data soucres (LDAP, JDBC, Active Directory...
Perform access control based on roles or fine grained permissions, also using plug...
Secure data with the easiest possible Cryptography API’s available, giving you...
Use sessions in any environment, even outside web or EJB containers. Easily...
Save development time with innovative approaches that easily handle web specific...
API’s giving you power and simplicty beyond what Java provides by default...网上大多数介绍Apache Shiro的资料都是使用ini文件的简单配置为例,很少用讲到如何配合数据库来实现用户认证的。我也是刚刚开始接触Shiro,在这里介绍一个入门级别的Shiro+Mysql的配置方法,这个方法仅仅是个开始,并没有和Web,Spring,Mybatis等框架进行整合,后续我还会继续和大家分享我的学习过程及心得。 now we can start the things that we really care about. 数据库中创建一个用户表,字段可以很简单。CREATE TABLE `sec_user` (
`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(64) COLLATE utf8_bin DEFAULT NULL,
`password` varchar(128) COLLATE utf8_bin DEFAULT NULL,
`created_time` datetime DEFAULT NULL,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin 在表中插入一条记录,用户名:chris.mao.,密码:cmao 在resources目录下创建一个ini文件,配置Shiro(后续文件会将此文件内容移至XML文件中)。在这个配置文件中我们要设置数据源,以及用户认证时使用数据库查询语句。这里用到了Shiro中自带的JdbcRealm类。[main]
dataSource=org.springframework.jdbc.datasource.DriverManagerDataSource
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql://127.0.0.1:3306/YOUR_DATABASE_NAME
dataSource.username=YOUR_USERNAME
dataSource.password=YOUR_PASSWORD
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.dataSource=$dataSource
jdbcRealm.authenticationQuery = SELECT password FROM sec_user WHERE user_name = ?
securityManager.realms=$jdbcRealm关于用户认证的查询语句,我在这里多说两句,小伙伴们不要嫌我啰嗦。我们只需要以用户名为查询条件,查询出密码字段即可,如果您在select后面使用了星号(*)或是查询字段多于一个,都无法通过用户认证 。配置文件写好后,我们就可以动手写个测试方法,来验证是否可以实现用户认证功能了。 package com.emerons.
import static org.junit.Assert.*;
import org.apache.shiro.SecurityU
import org.apache.shiro.authc.DisabledAccountE
import org.apache.shiro.authc.ExcessiveAttemptsE
import org.apache.shiro.authc.ExpiredCredentialsE
import org.apache.shiro.authc.IncorrectCredentialsE
import org.apache.shiro.authc.LockedAccountE
import org.apache.shiro.authc.UnknownAccountE
import org.apache.shiro.authc.UsernamePasswordT
import org.apache.shiro.config.IniSecurityManagerF
import org.apache.shiro.mgt.SecurityM
import org.apache.shiro.subject.S
import org.apache.shiro.util.F
import org.junit.A
import org.junit.B
import org.junit.T
public class JdbcRealmTest {
public void setUp() throws Exception {
public void tearDown() throws Exception {
public void test() {
// 1.获取SecurityManager工厂,此处使用ini配置文件初始化SecurityManager
Factory&SecurityManager& factory = new IniSecurityManagerFactory("classpath:shiro-jdbc-realm.ini");
// 2.获取SecurityManager实例,并绑定到SecurityUtils
SecurityManager sm = factory.getInstance();
SecurityUtils.setSecurityManager(sm);
// 3.得到Subject
Subject subject = SecurityUtils.getSubject();
// 4.创建用户登录凭证
UsernamePasswordToken token = new UsernamePasswordToken("chris.", "chrismao");
// 5.登录,如果登录失败会抛出不同的异常,根据异常输出失败原因
subject.login(token);
// 6.判断是否成功登录
assertEquals(true, subject.isAuthenticated());
System.out.println("登录成功!!");
// 7.注销用户
subject.logout();
} catch (IncorrectCredentialsException e) {
System.out.println("登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.");
} catch (ExcessiveAttemptsException e) {
System.out.println("登录失败次数过多");
} catch (LockedAccountException e) {
System.out.println("帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.");
} catch (DisabledAccountException e) {
System.out.println("帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.");
} catch (ExpiredCredentialsException e) {
System.out.println("帐号已过期. the account for username " + token.getPrincipal() + "
was expired.");
} catch (UnknownAccountException e) {
System.out.println("帐号不存在. There is no user with username of " + token.getPrincipal());
} 运行测试代码,得到如下输出:INFO : org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver
INFO : org.apache.shiro.realm.AuthorizingRealm - No cache or cacheManager properties have been set.
Authorization cache cannot be obtained.
INFO : org.apache.shiro.config.IniSecurityManagerFactory - Realms have been explicitly set on the SecurityManager instance - auto-setting of realms will not occur.
INFO : org.apache.shiro.session.mgt.AbstractValidatingSessionManager - Enabling session validation scheduler...
登录成功!!
INFO : org.apache.shiro.realm.AuthorizingRealm - No cache or cacheManager properties have been set.
Authorization cache cannot be obtained.
我们从日志上可以看到,程序加载了Jdbc驱动,明确指定了realm,这说明我们的Shiro配置文件加载成功。最后看到输出了“登录成功”说明这个认证功能已经实现了。大家也可以试着修改测试代码用的用户名或是密码,可以在控制台看到类似下面的输出,说明也可以抛出正确的异常。INFO : org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver
INFO : org.apache.shiro.realm.AuthorizingRealm - No cache or cacheManager properties have been set.
Authorization cache cannot be obtained.
INFO : org.apache.shiro.config.IniSecurityManagerFactory - Realms have been explicitly set on the SecurityManager instance - auto-setting of realms will not occur.
登录密码错误. Password for account chris. was incorrect.
至此,使用Shiro + Mysql实现用户认证(Authentication)的功能已经完成。大家可以在这个基础上,完善实现角色授权(Authroization),操作允可(Permission)等功能,参见《》
(三) shiro通过jdbc连接数据库
shiro代码参考java1234网站《一头扎进shiro》视频敲出来的,原理这些请参视频 ,
2 项目结构图
JdbcRealmTe...
Shiro连接数据库验证
1、要使用的数据表DROP DATABASE IF EXISTS
CREATE DATABASE shirodb CHARACTER SET UTF8 ;
USE shirodb ...
整合shiro时,登录请求无法捕捉UnknownAccountException
代码写累了,关于整合shiro,写个文章记录下一个简单但是困扰了我好久的问题:无论登陆时包什么异常,在controll中获取的都是异常的父类AuthenticationException。
框架使用...
Shiro:org.apache.shiro.authc.AuthenticationException
org.apache.shiro.authc.AuthenticationException: Authentication failed for token submission
[org.apa...
org.apache.shiro.authc.AuthenticationException: There was a SQL error while authenticating user [zh...
Shiro 是一个 Apache Incubator 项目,旨在简化身份验证和授权。
http://shiro.apache.org/
Apache Shiro 是一个强大而灵活的开源安全框架,它干净利落地处理身份认证,授权,企业会话管理和加密。
Apache Shiro 的首要目标是易于使用和理解。安全有时候是很复杂的,甚至是痛苦的...
SpringMVC整合Shiro权限框架
最近在学习Shiro,首先非常感谢开涛大神的《跟我学Shiro》系列,在我学习的过程中发挥了很大的指导作用。学习一个新的东西首先就是做一个demo,多看不如多敲,只有在实践中才能发现自己的欠缺,下面记...
没有更多推荐了,【分布式、微服务、云架构、dubbo+zookeeper+springmvc+mybatis+shiro+redis】分布式大型互联网企业架构!
【分布式、微服务、云架构、dubbo+zookeeper+springmvc+mybatis+shiro+redis】分布式大型互联网企业架构!
框架简介--主要定位于互联网企业架构,已内置企业信息化系统的基础功能和高效的代码生成工具,包括:系统权限组件、数据权限组件、数据字典组件、核心工具 组件、视图操作组件、工作流组件组件、代码生成等。采用分层设计、双重验证、提交数据安全编码、密码加密、访问验证、数据权限验证。
框架简介--主要定位于互联网企业架构,已内置企业信息化系统的基础功能和高效的代码生成工具,包括:系统权限组件、数据权限组件、数据字典组件、核心工具 组件、视图操作组件、工作流组件组件、代码生成等。采用分层设计、双重验证、提交数据安全编码、密码加密、访问验证、数据权限验证。平台简介
是一个分布式的框架,提供项目模块化、服务化、热插拔的思想,高度封装安全性的Java EE快速开发平台。
本身集成Dubbo服务管控、Zookeeper注册中心、Redis分布式缓存技术、FastDFS分布式文件系统、ActiveMQ异步消息中间件、Nginx负载均衡等分布式技术
使用Maven做项目管理,项目模块化,提高项目的易开发性、扩展性
以Spring Framework为核心容器,Spring MVC为模型视图控制器,MyBatis为数据访问层, Apache Shiro为权限授权层,Ehcahe对常用数据进行缓存,Activit为工作流引擎等。
前端集成Bootstrap4 metronic框架,UI响应式、扁平化布局,适应所有PC、Pad、Anroid、ios 移动设备等。
主要定位于互联网企业架构,已内置企业信息化系统的基础功能和高效的代码生成工具,包括:系统权限组件、数据权限组件、数据字典组件、核心工具 组件、视图操作组件、工作流组件、代码生成等。采用分层设计、双重验证、提交数据安全编码、密码加密、访问验证、数据权限验证。
目前包括以下模块项目,后台系统管理系统,RestFul独立服务系统、Scheduler定时调度系统、内容管理(CMS)系统、在线办公(OA)系统、我的待办(Task服务)、我的收藏(Bookmark服务)。
后台管理系统包括企业组织架构(用户管理、机构管理、区域管理)、菜单管理、角色权限管理、字典管理等功能;
RestFul独立提供标准Rest服务API,您可以快速实现自己的业务,提供需要的服务;
Quartz定时调度系统可以动态配置您的任务规则等;
内容管理(CMS)系统,包括内容管理,栏目管理、站点管理、公共留言、文件管理、前端网站展示等功能;
在线办公(OA)系统,主要提供简单的流程实例。
提供了常用工具进行封装,包括日志工具、缓存工具、服务器端验证、数据字典、当前组织机构数据(用户、机构、区域)以及其它常用小工具等。另外 还提供一个强大的在线 代码生成 工具,此工具提供简单的单表、一对多、树结构功能的生成,如果对外观要求不是很高,生成的功能就可以用了。使用了基础框架,可以提高快速开发效 率。
内置功能(只列了一部分功能)
1.用户管理:用户是系统操作者,该功能主要完成系统用户配置。
2.机构管理:配置系统组织机构(公司、部门、小组),树结构展现,可随意调整上下级。
3.区域管理:系统城市区域模型,如:国家、省市、地市、区县的维护。
4.菜单管理:配置系统菜单,操作权限,按钮权限标识等。
5.角色管理:角色菜单权限分配、设置角色按机构进行数据范围权限划分。
6.字典管理:对系统中经常使用的一些较为固定的数据进行维护,如:是否、男女、类别、级别等。
7.操作日志:系统正常操作日志记录和查询;系统异常信息日志记录和查询。
8.连接池监视:监视当期系统数据库连接池状态,可进行分析SQL找出系统性能瓶颈。
9.工作流引擎:实现业务工单流转、在线流程设计器。
1.Eclipse IDE:采用Maven项目管理,模块化。
2.代码生成:通过界面方式简单配置,自动生成相应代码,目前包括三种生成方式(增删改查):单表、一对多、树结构。生成后的代码如果不需要注意美观程度,生成后即可用。
技术选型(只列了一部分技术)
服务框架:Dubbo、zookeeper、Rest服务
缓存:Redis、ehcache
消息中间件:ActiveMQ
负载均衡:Nginx
分布式文件:FastDFS
数据库连接池:Alibaba Druid 1.0
核心框架:Spring framework
安全框架:Apache Shiro 1.2
视图框架:Spring MVC 4.0
服务端验证:Hibernate Validator 5.1
布局框架:SiteMesh 2.4
工作流引擎:Activiti 5.15
任务调度:quartz 1.8.5
持久层框架:MyBatis 3.2
日志管理:SLF4J 1.7、Log4j
工具类:Apache Commons、Jackson 2.2、Xstream 1.4、Dozer 5.3、POI
JS框架:JQuery 1.9。
CSS框架: Bootstrap 4 metronic
客户端验证:JQuery Validation Plugin。
富文本:CKEcitor
文件管理:CKFinder
动态页签:Jerichotab
数据表格:jqGrid
对话框:jQuery jBox
树结构控件:jQuery zTree
其他组件:Bootstrap 4 metronic
服务器中间件:Tomcat 6、7、Jboss 7、WebLogic 10、WebSphere 8
数据库支持:目前仅提供mysql数据库的支持,但不限于数据库,下个版本升级多数据源切换和数据库读写分离: 如:Oracle、SqlServer、H2等
支持开发环境:Eclipse、MyEclipse、Ras、Idea等
经典介绍:
JEESZ驱动式项目构建
内置高效可靠的代码生成器
支持多种数据模型,根据数据库表生成常规重复性代码,使研发工程师更专注于业务逻辑代码的实现,大幅提升其工作效率,解放其重复性工作
开源规范化项目管理解决方案,实现软件流水线式生产,保证正确性、可靠性
向导式创建、导入项目,集成版本控制(GIT/SVN)、项目管理(Trac/Redmine)、代码质量(Sonar)、持续集成(Jenkins)
私有部署,统一管理,为开发者而生
基于Bootstrap4
简洁、直观、强悍最受欢迎的 HTML、CSS 和 JS 框架,用于开发响应式布局、移动设备优先的 WEB 项目。
为所有开发者、所有应用场景而设计。
让前端开发更快速、简单。所有开发者都能快速上手、所有设备都可以适配、所有项目都适用。
分布式服务:Dubbo+Zookeeper+Proxy+Restful
分布式消息中间件:KafKa+Flume+Zookeeper
分布式缓存:Redis
分布式文件:FastDFS
负载均衡:Keepalived+Nginx+Proxy(三重负载)
子系统:后台管理系统、Restfu服务系统、Dubbo服务/管控/监控中心
Zookeeper注册中心、报表分析系统、日志记录系统、定时调度系统
搜索引擎系统、分布式文件系统、消息系统、SSO单点登录系统
SOA管控平台、UI组件系统、OA办公系统、CMS新闻发布系统
支付系统、数据库配置系统、工作流系统、云服务平台
用云栖社区APP,舒服~
【云栖快讯】Apache旗下顶级开源盛会 HBasecon Asia 2018将于8月17日在京举行,现场仅600席,免费赠票领取入口&&
喜欢关注哦
充分利用阿里云现有资源管理和服务体系,引入中间件成熟的整套分布式计算框架,以应用为中心,帮助...
支持 PB 级数据存储的海量分布式关系型数据库。它支持 MySQL 数据库接口,采用可扩展的...
消息队列(Message Queue,简称MQ)是阿里云商用的专业消息中间件,是企业级互联网...
阿里云总监课正式启航springboot学习笔记:11.springboot+shiro+mysql+mybatis(通用mapper)+freemarker+ztree+layui实现通用的java后台管理系统(权限管理+用户管理+菜单管理)-企业网站小程序定制-Erlo.vip
springboot学习笔记:11.springboot+shiro+mysql+mybatis(通用mapper)+freemarker+ztree+layui实现通用的java后台管理系统(权限管理+用户管理+菜单管理)
时间: 13:34 & 阅读:367次 & 来源:博客园页面报错
经过前10篇文章,我们已经可以快速搭建一个springboot的web项目;
今天,我们在上一节基础上继续集成shiro框架,实现一个可以通用的后台管理系统;包括用户管理,角色管理,菜单管理三大系统常用管理模块;
二.数据库表准备:
要想实现用户管理+角色管理+菜单管理三大模块,基本上我们常用的解决方案就是如下五个表(sql脚本在最后):
三.集成shiro和配置
1.添加pom依赖。
&dependency&
&groupId&org.apache.shiro&/groupId&
&artifactId&shiro-core&/artifactId&
&version&1.4.0&/version&
&/dependency&
&dependency&
&groupId&org.apache.shiro&/groupId&
&artifactId&shiro-spring&/artifactId&
&version&1.4.0&/version&
&/dependency&
2.编辑shiro配置类:ShiroConfig.java
package com.zjt.
import com.zjt.realm.MyR
import org.apache.shiro.mgt.SecurityM
import org.apache.shiro.spring.LifecycleBeanPostP
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceA
import org.apache.shiro.spring.web.ShiroFilterFactoryB
import org.apache.shiro.web.mgt.CookieRememberMeM
import org.apache.shiro.web.mgt.DefaultWebSecurityM
import org.apache.shiro.web.servlet.SimpleC
import org.springframework.context.annotation.B
import org.springframework.context.annotation.C
import java.util.LinkedHashM
import java.util.M
* @Author: Zhaojiatao
* @Description: Shiro配置类
* @Date: Created in
@Configuration
public class ShiroConfig {
* ShiroFilterFactoryBean 处理拦截资源文件问题。
* 注意:单独一个ShiroFilterFactoryBean配置是或报错的,以为在
* 初始化ShiroFilterFactoryBean的时候需要注入:SecurityManager
* Filter Chain定义说明 1、一个URL可以配置多个Filter,使用逗号分隔 2、当设置多个过滤器时,全部验证通过,才视为通过
* 3、部分过滤器可指定参数,如perms,roles
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 必须设置 SecurityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
//shiroFilterFactoryBean.setLoginUrl("/login.ftl");
//配置退出过滤器,其中的具体的退出代码Shiro已经替我们实现了
shiroFilterFactoryBean.setLoginUrl("/tologin");
shiroFilterFactoryBean.setUnauthorizedUrl("/tologin");
// 拦截器.
Map&String, String& filterChainDefinitionMap = new LinkedHashMap&String, String&();
//配置记住我或认证通过可以访问的地址(配置不会被拦截的链接 顺序判断)
filterChainDefinitionMap.put("/static#zs#*", "anon");
filterChainDefinitionMap.put("/user/login", "anon");
filterChainDefinitionMap.put("/drawImage", "anon");
// 配置退出过滤器,其中的具体的退出代码Shiro已经替我们实现了
filterChainDefinitionMap.put("/admin/user/logout", "logout");
// &!-- 过滤链定义,从上向下顺序执行,一般将 #zs#*放在最为下边 --&:这是一个坑呢,一不小心代码就不好使了;
// &!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问--&
filterChainDefinitionMap.put("#zs#*", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryB
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 设置realm.
securityManager.setRealm(myRealm());
//注入记住我管理器;
securityManager.setRememberMeManager(rememberMeManager());
return securityM
* 身份认证 (这个需要自己写,账号密码校验;权限等)
public MyRealm myRealm() {
MyRealm myRealm = new MyRealm();
return myR
* Shiro生命周期处理器
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
return new LifecycleBeanPostProcessor();
* 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
* 配置以下两个bean(DefaultAdvisorAutoProxyCreator(可选)和AuthorizationAttributeSourceAdvisor)即可实现此功能
* 不要使用 DefaultAdvisorAutoProxyCreator 会出现二次代理的问题,这里不详述
#zs# @Bean
@DependsOn({"lifecycleBeanPostProcessor"})
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyC
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
return authorizationAttributeSourceA
* cookie对象;
* 记住密码实现起来也是比较简单的,主要看下是如何实现的。
public SimpleCookie rememberMeCookie(){
System.out.println("ShiroConfiguration.rememberMeCookie()");
//这个参数是cookie的名称,对应前端的checkbox的name = rememberMe
SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
//&!-- 记住我cookie生效时间30天 ,单位秒;--&
simpleCookie.setMaxAge(259200);
return simpleC
* cookie管理对象;
public CookieRememberMeManager rememberMeManager(){
System.out.println("ShiroConfiguration.rememberMeManager()");
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
return cookieRememberMeM
3.实现自定义MyRealm.java
package com.zjt.
import com.zjt.entity.T
import com.zjt.entity.T
import com.zjt.entity.T
import com.zjt.mapper.TmenuM
import com.zjt.mapper.TroleM
import com.zjt.mapper.TuserM
import com.zjt.mapper.TuserroleM
import org.apache.shiro.SecurityU
import org.apache.shiro.authc.AuthenticationE
import org.apache.shiro.authc.AuthenticationI
import org.apache.shiro.authc.AuthenticationT
import org.apache.shiro.authc.SimpleAuthenticationI
import org.apache.shiro.authz.AuthorizationI
import org.apache.shiro.authz.SimpleAuthorizationI
import org.apache.shiro.realm.AuthorizingR
import org.apache.shiro.subject.PrincipalC
import tk.mybatis.mapper.entity.E
import javax.annotation.R
import java.util.HashS
import java.util.L
import java.util.S
* 自定义Realm
* @author zjt
public class MyRealm extends AuthorizingRealm{
private TuserMapper tuserM
private TroleMapper troleM
private TuserroleMapper tuserroleM
private TmenuMapper tmenuM
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String userName=(String) SecurityUtils.getSubject().getPrincipal();
//User user=userRepository.findByUserName(userName);
//根据用户名查询出用户记录
Example tuserExample=new Example(Tuser.class);
tuserExample.or().andEqualTo("userName",userName);
Tuser user=tuserMapper.selectByExample(tuserExample).get(0);
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
//List&Role& roleList=roleRepository.findByUserId(user.getId());
List&Trole& roleList = troleMapper.selectRolesByUserId(user.getId());
Set&String& roles=new HashSet&String&();
if(roleList.size()&0){
for(Trole role:roleList){
roles.add(role.getName());
//List&Tmenu& menuList=menuRepository.findByRoleId(role.getId());
//根据角色id查询所有资源
List&Tmenu& menuList=tmenuMapper.selectMenusByRoleId(role.getId());
for(Tmenu menu:menuList){
info.addStringPermission(menu.getName()); // 添加权限
info.setRoles(roles);
* 权限认证
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName=(String)token.getPrincipal();
//User user=userRepository.findByUserName(userName);
Example tuserExample=new Example(Tuser.class);
tuserExample.or().andEqualTo("userName",userName);
Tuser user=tuserMapper.selectByExample(tuserExample).get(0);
if(user!=null){
AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),"xxx");
return authcI
return null;
4.登录、退出、权限限制
登录:subject.login(token);
退出:SecurityUtils.getSubject().logout();
在方法前使用shiro注解实现权限校验,如:@RequiresPermissions(value = {"用户管理"}) 表示当前用户必须拥有用户管理的权限;
四、前端实现及效果展示
源码:srcmainresourcestemplateslogin.ftl
用户名:admin
&2、系统管理-菜单管理
菜单管理页面源码:srcmainresourcestemplatespowermenu.ftl
里面使用了ztree实现的菜单的新建、编辑、删除;
菜单管理的后台接口:com.zjt.web.MenuController.java
注意一级菜单在顶部显示,且一级菜单名不可为纯数字;
二级三级菜单在左侧显示,且最多只能到三级菜单;
&3、系统管理-角色管理
srcmainresourcestemplatespowerrole.ftl
com.zjt.web.RoleAdminController.java
页面使用了jqgrid表格插件;
并可以设置每个角色对应的菜单权限:
4、系统管理-用户管理
&srcmainresourcestemplatespoweruser.ftl
&com.zjt.web.UserAdminController.java
选择行后可以设置角色:
&本后台管理系统可作为通用的后台管理系统,她简单纯净;内置完善的菜单管理+角色管理+用户管理;拿来即用;
使用技术涉及:
springboot+springmvc+mysql+mybatis+通用mapper+分页插件+shiro+freemarker+layui+ztree
&其中layui模板使用的是layuicms2.0
本项目源码:
&https://github.com/zhaojiatao/springboot-zjt-chapter10-springboot-mysql-mybatis-shiro-freemarker-layui.git
&sql脚本含在项目sql文件夹中
还没有评论留言,赶紧来抢楼吧~~
Erlo大厅()
* 这里是“Erlo大厅”,在这发言所有人都可以看到。只保留当天信息
Erlo.vip 15:53:38Hello、欢迎使用Erlo大厅,这里是个吐槽的地方。
回车键发送

我要回帖

更多关于 shiro按钮权限 的文章

 

随机推荐