SpringBoot整合Shiro的代码详解
shiro是一个权限框架,具体的使用可以查看其官网 它提供了很方便的权限认证和登录的功能.
而springboot作为一个开源框架,必然提供了和shiro整合的功能!接下来就用springboot结合springmvc,mybatis,整合shiro完成对于用户登录的判定和权限的验证.
1.准备数据库表结构
这里主要涉及到五张表:用户表,角色表(用户所拥有的角色),权限表(角色所涉及到的权限),用户-角色表(用户和角色是多对多的),角色-权限表(角色和权限是多对多的).表结构建立的sql语句如下:
create table `module` ( `mid` int(11) not null auto_increment, `mname` varchar(255) default null, primary key (`mid`) ) engine=innodb auto_increment=5 default charset=utf8; -- ---------------------------- -- records of module -- ---------------------------- insert into `module` values ('1', 'add'); insert into `module` values ('2', 'delete'); insert into `module` values ('3', 'query'); insert into `module` values ('4', 'update'); -- ---------------------------- -- table structure for module_role -- ---------------------------- drop table if exists `module_role`; create table `module_role` ( `rid` int(11) default null, `mid` int(11) default null, key `rid` (`rid`), key `mid` (`mid`), constraint `mid` foreign key (`mid`) references `module` (`mid`), constraint `rid` foreign key (`rid`) references `role` (`rid`) ) engine=innodb default charset=utf8; -- ---------------------------- -- records of module_role -- ---------------------------- insert into `module_role` values ('1', '1'); insert into `module_role` values ('1', '2'); insert into `module_role` values ('1', '3'); insert into `module_role` values ('1', '4'); insert into `module_role` values ('2', '1'); insert into `module_role` values ('2', '3'); -- ---------------------------- -- table structure for role -- ---------------------------- drop table if exists `role`; create table `role` ( `rid` int(11) not null auto_increment, `rname` varchar(255) default null, primary key (`rid`) ) engine=innodb auto_increment=3 default charset=utf8; -- ---------------------------- -- records of role -- ---------------------------- insert into `role` values ('1', 'admin'); insert into `role` values ('2', 'customer'); -- ---------------------------- -- table structure for user -- ---------------------------- drop table if exists `user`; create table `user` ( `uid` int(11) not null auto_increment, `username` varchar(255) default null, `password` varchar(255) default null, primary key (`uid`) ) engine=innodb auto_increment=3 default charset=utf8; -- ---------------------------- -- records of user -- ---------------------------- insert into `user` values ('1', 'hlhdidi', '123'); insert into `user` values ('2', 'xyycici', '1992'); -- ---------------------------- -- table structure for user_role -- ---------------------------- drop table if exists `user_role`; create table `user_role` ( `uid` int(11) default null, `rid` int(11) default null, key `u_fk` (`uid`), key `r_fk` (`rid`), constraint `r_fk` foreign key (`rid`) references `role` (`rid`), constraint `u_fk` foreign key (`uid`) references `user` (`uid`) ) engine=innodb default charset=utf8; -- ---------------------------- -- records of user_role -- ---------------------------- insert into `user_role` values ('1', '1'); insert into `user_role` values ('2', '2');
2.建立maven工程,建立实体类,搭建mybatis开发环境
maven工程的基本目录如下:
为了方便,直接在父工程中,导入全部的依赖:
<!-- springboot的启动所需配置.包括自动配置,封装jar包等等 --> <parent> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-parent</artifactid> <version>1.4.0.release</version> </parent> <properties> <java.version>1.7</java.version> <project.build.sourceencoding>utf-8</project.build.sourceencoding> </properties> <dependencies> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-devtools</artifactid> <optional>true</optional> <scope>true</scope> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <scope>runtime</scope> </dependency> <dependency> <groupid>com.alibaba</groupid> <artifactid>druid</artifactid> <version>1.0.18</version> </dependency> <dependency> <groupid>org.apache.commons</groupid> <artifactid>commons-lang3</artifactid> <version>3.4</version> </dependency> <dependency> <groupid>org.apache.commons</groupid> <artifactid>commons-pool2</artifactid> </dependency> <dependency> <groupid>org.mybatis.spring.boot</groupid> <artifactid>mybatis-spring-boot-starter</artifactid> <version>1.1.1</version> </dependency> <dependency> <groupid>com.alibaba</groupid> <artifactid>druid</artifactid> <version>1.0.18</version> </dependency> <dependency> <groupid>org.apache.commons</groupid> <artifactid>commons-lang3</artifactid> <version>3.4</version> </dependency> <dependency> <groupid>org.apache.commons</groupid> <artifactid>commons-pool2</artifactid> </dependency> <!-- shiro spring. --> <dependency> <groupid>org.apache.shiro</groupid> <artifactid>shiro-core</artifactid> <version>1.2.2</version> </dependency> <dependency> <groupid>org.apache.shiro</groupid> <artifactid>shiro-spring</artifactid> <version>1.2.2</version> </dependency> <!-- shiro ehcache --> <dependency> <groupid>org.apache.shiro</groupid> <artifactid>shiro-ehcache</artifactid> <version>1.2.2</version> </dependency> <!-- 包含支持ui模版(velocity,freemarker,jasperreports), 邮件服务, 脚本服务(jruby), 缓存cache(ehcache), 任务计划scheduling(uartz)。 --> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-context-support</artifactid> </dependency> <!-- servlet 依赖. --> <dependency> <groupid>javax.servlet</groupid> <artifactid>javax.servlet-api</artifactid> <scope>provided</scope> </dependency> <dependency> <groupid>javax.servlet</groupid> <artifactid>jstl</artifactid> </dependency> <!-- tomcat 的支持.--> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-tomcat</artifactid> <scope>provided</scope> </dependency> <dependency> <groupid>org.apache.tomcat.embed</groupid> <artifactid>tomcat-embed-jasper</artifactid> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-maven-plugin</artifactid> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> <configuration> <!--fork : 如果没有该项配置则devtools不会起作用,即应用不会restart --> <fork>true</fork> </configuration> </plugin> </plugins> </build> <modules> <module>spring-boot-shiro-dao</module> <module>spring-boot-shiro-service</module> <module>spring-boot-shiro-web</module> </modules>
可以看出这里采用的是阿里巴巴的druid数据库.在spring-boot-shiro-web下建立application.properties文件.它主要配置对于数据库信息和jsp的支持:
##tomcat## server.tomcat.uri-encoding=utf-8 ##druid## spring.datasource.type=com.alibaba.druid.pool.druiddatasource spring.datasource.driver-class-name=com.mysql.jdbc.driver spring.datasource.url=jdbc:mysql://localhost:3306/test?characterencoding=utf-8 spring.datasource.username=root spring.datasource.password=root spring.datasource.initialsize=5 spring.datasource.minidle=5 spring.datasource.maxactive=20 spring.datasource.maxwait=60000 spring.datasource.timebetweenevictionrunsmillis=60000 spring.datasource.minevictableidletimemillis=300000 spring.datasource.validationquery=select 1 from dual spring.datasource.testwhileidle=true spring.datasource.testonborrow=false spring.datasource.testonreturn=false spring.datasource.poolpreparedstatements=true spring.datasource.maxpoolpreparedstatementperconnectionsize=20 spring.datasource.filters=stat,wall,log4j spring.datasource.connectionproperties=druid.stat.mergesql=true;druid.stat.slowsqlmillis=5000 spring.datasource.useglobaldatasourcestat=true ##jsp## spring.mvc.view.prefix=/jsp/ spring.mvc.view.suffix=.jsp
在spring-boot-shiro-web下建立数据库连接池的配置类完成对于数据库连接池的配置:
/** * 数据库连接池&mybatis配置类 * @author administrator * */ @configuration public class druidconfiguation { @bean public servletregistrationbean statviewservle(){ servletregistrationbean servletregistrationbean = new servletregistrationbean(new statviewservlet(),"/druid/*"); //白名单: servletregistrationbean.addinitparameter("allow","192.168.1.218,127.0.0.1"); //ip黑名单 (存在共同时,deny优先于allow) : 如果满足deny的即提示:sorry, you are not permitted to view this page. servletregistrationbean.addinitparameter("deny","192.168.1.100"); //登录查看信息的账号密码. servletregistrationbean.addinitparameter("loginusername","druid"); servletregistrationbean.addinitparameter("loginpassword","12345678"); //是否能够重置数据. servletregistrationbean.addinitparameter("resetenable","false"); return servletregistrationbean; } @bean public filterregistrationbean statfilter(){ filterregistrationbean filterregistrationbean = new filterregistrationbean(new webstatfilter()); //添加过滤规则. filterregistrationbean.addurlpatterns("/*"); //添加不需要忽略的格式信息. filterregistrationbean.addinitparameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterregistrationbean; } @bean persistenceexceptiontranslationpostprocessor persistenceexceptiontranslationpostprocessor(){ return new persistenceexceptiontranslationpostprocessor(); } //配置数据库的基本链接信息 @bean(name = "datasource") @primary @configurationproperties(prefix = "spring.datasource") //可以在application.properties中直接导入 public datasource datasource(){ return datasourcebuilder.create().type(com.alibaba.druid.pool.druiddatasource.class).build(); } @bean public sqlsessionfactorybean sqlsessionfactory(@qualifier("datasource") datasource datasource) { sqlsessionfactorybean bean=new sqlsessionfactorybean(); bean.setdatasource(datasource); return bean; } }
接着在spring-boot-shiro-web下建立application类:
@springbootapplication @enabletransactionmanagement @mapperscan("com.xyy.springboot.shiro.mapper")//配置mybatis包扫描 public class application { public static void main(string[] args) { springapplication.run(application.class, args); } }
紧接着,我们根据数据库的表结构在spring-boot-shiro-dao的项目下建立实体类user,role,module.它们的意义在上文中已经说明了:
接着就可以书写mapper了,注意,mapper所在的位置需要和application类中配置的包扫描的位置保持一致,我们的需求是根据用户名在数据库中查询出指定的用户表的记录,与此同时查询出对应的角色以及角色所对应的权限,并且封装到实体类user中.usermapper接口如下:
usermapper.xml如下:
<mapper namespace="com.xyy.springboot.shiro.mapper.usermapper"> <resultmap type="com.xyy.springboot.shiro.pojo.user" id="usermap"> <id property="uid" column="uid"/> <result property="username" column="username"/> <result property="password" column="password"/> <collection property="roles" oftype="com.xyy.springboot.shiro.pojo.role"> <id property="rid" column="rid"/> <result property="rname" column="rname"/> <collection property="modules" oftype="com.xyy.springboot.shiro.pojo.module"> <id property="mid" column="mid"/> <result property="mname" column="mname"/> </collection> </collection> </resultmap> <select id="findbyusername" parametertype="string" resultmap="usermap"> select u.*,r.*,m.* from user u inner join user_role ur on ur.uid=u.uid inner join role r on r.rid=ur.rid inner join module_role mr on mr.rid=r.rid inner join module m on mr.mid=m.mid where username=#{username}; </select> </mapper>
在spring-boot-shiro-service建立userservice和userserviceimpl,完成业务层对于mapper的调用:
紧接着就是重点啦!我们需要在spring-boot-shiro-web工程下面建立两个类,这也是shiro中唯一需要程序员编写的两个类:类authrealm完成根据用户名去数据库的查询,并且将用户信息放入shiro中,供第二个类调用.credentialsmatcher,完成对于密码的校验.其中用户的信息来自shiro.authrealm类如下:
public class authrealm extends authorizingrealm{ @autowired private userservice userservice; //认证.登录 @override protected authenticationinfo dogetauthenticationinfo(authenticationtoken token) throws authenticationexception { usernamepasswordtoken utoken=(usernamepasswordtoken) token;//获取用户输入的token string username = utoken.getusername(); user user = userservice.finduserbyusername(username); return new simpleauthenticationinfo(user, user.getpassword(),this.getclass().getname());//放入shiro.调用credentialsmatcher检验密码 } //授权 @override protected authorizationinfo dogetauthorizationinfo(principalcollection principal) { user user=(user) principal.fromrealm(this.getclass().getname()).iterator().next();//获取session中的用户 list<string> permissions=new arraylist<>(); set<role> roles = user.getroles(); if(roles.size()>0) { for(role role : roles) { set<module> modules = role.getmodules(); if(modules.size()>0) { for(module module : modules) { permissions.add(module.getmname()); } } } } simpleauthorizationinfo info=new simpleauthorizationinfo(); info.addstringpermissions(permissions);//将权限放入shiro中. return info; } }
授权的方法是在碰到<shiro:haspermission>标签的时候调用的,它会去检测shiro框架中的权限(这里的permissions)是否包含有该标签的name值,如果有,里面的内容显示,如果没有,里面的内容不予显示(这就完成了对于权限的认证.)下面是credentialsmatcher:
public class credentialsmatcher extends simplecredentialsmatcher{ @override public boolean docredentialsmatch(authenticationtoken token, authenticationinfo info) { usernamepasswordtoken utoken=(usernamepasswordtoken) token; //获得用户输入的密码:(可以采用加盐(salt)的方式去检验) string inpassword = new string(utoken.getpassword()); //获得数据库中的密码 string dbpassword=(string) info.getcredentials(); //进行密码的比对 return this.equals(inpassword, dbpassword); } }
接着就是shiro的配置类了,需要注意一点filterchaindefinitionmap必须是linkedhashmap因为它必须保证有序:
shiro的配置类如下:
/** * shiro的配置类 * @author administrator * */ @configuration public class shiroconfiguration { @bean(name="shirofilter") public shirofilterfactorybean shirofilter(@qualifier("securitymanager") securitymanager manager) { shirofilterfactorybean bean=new shirofilterfactorybean(); bean.setsecuritymanager(manager); //配置登录的url和登录成功的url bean.setloginurl("/login"); bean.setsuccessurl("/home"); //配置访问权限 linkedhashmap<string, string> filterchaindefinitionmap=new linkedhashmap<>(); filterchaindefinitionmap.put("/jsp/login.jsp*", "anon"); //表示可以匿名访问 filterchaindefinitionmap.put("/loginuser", "anon"); filterchaindefinitionmap.put("/logout*","anon"); filterchaindefinitionmap.put("/jsp/error.jsp*","anon"); filterchaindefinitionmap.put("/jsp/index.jsp*","authc"); filterchaindefinitionmap.put("/*", "authc");//表示需要认证才可以访问 filterchaindefinitionmap.put("/**", "authc");//表示需要认证才可以访问 filterchaindefinitionmap.put("/*.*", "authc"); bean.setfilterchaindefinitionmap(filterchaindefinitionmap); return bean; } //配置核心安全事务管理器 @bean(name="securitymanager") public securitymanager securitymanager(@qualifier("authrealm") authrealm authrealm) { system.err.println("--------------shiro已经加载----------------"); defaultwebsecuritymanager manager=new defaultwebsecuritymanager(); manager.setrealm(authrealm); return manager; } //配置自定义的权限登录器 @bean(name="authrealm") public authrealm authrealm(@qualifier("credentialsmatcher") credentialsmatcher matcher) { authrealm authrealm=new authrealm(); authrealm.setcredentialsmatcher(matcher); return authrealm; } //配置自定义的密码比较器 @bean(name="credentialsmatcher") public credentialsmatcher credentialsmatcher() { return new credentialsmatcher(); } @bean public lifecyclebeanpostprocessor lifecyclebeanpostprocessor(){ return new lifecyclebeanpostprocessor(); } @bean public defaultadvisorautoproxycreator defaultadvisorautoproxycreator(){ defaultadvisorautoproxycreator creator=new defaultadvisorautoproxycreator(); creator.setproxytargetclass(true); return creator; } @bean public authorizationattributesourceadvisor authorizationattributesourceadvisor(@qualifier("securitymanager") securitymanager manager) { authorizationattributesourceadvisor advisor=new authorizationattributesourceadvisor(); advisor.setsecuritymanager(manager); return advisor; } }
这样,shiro的配置就完成了!紧接着建立页面.login.jsp用于用户登录,index.jsp是用户主页,在没有登录的情况下是进不去的.内容分别如下:
index.jsp
<h1>欢迎${user.username }光临!请选择你的操作:</h1><br> <ul> <shiro:haspermission name="add"><li>增加</li></shiro:haspermission> <shiro:haspermission name="delete"><li>删除</li></shiro:haspermission> <shiro:haspermission name="update"><li>修改</li></shiro:haspermission> <shiro:haspermission name="query"><li>查询</li></shiro:haspermission> </ul> <a href="${pagecontext.request.contextpath }/logout" rel="external nofollow" >点我注销</a>
login.jsp
<h1>欢迎登录!${user.username }</h1> <form action="${pagecontext.request.contextpath }/loginuser" method="post"> <input type="text" name="username"><br> <input type="password" name="password"><br> <input type="submit" value="提交"> </form>
ok,紧接着就是建立logincontroller去测试结果了!这里需要注意,我们和shiro框架的交互完全通过subject这个类去交互,用它完成登录,注销,获取当前的用户对象等操作:
@controller public class logincontroller { @requestmapping("/login") public string login() { return "login"; } @requestmapping("/loginuser") public string loginuser(string username,string password,httpsession session) { usernamepasswordtoken usernamepasswordtoken=new usernamepasswordtoken(username,password); subject subject = securityutils.getsubject(); try { subject.login(usernamepasswordtoken); //完成登录 user user=(user) subject.getprincipal(); session.setattribute("user", user); return "index"; } catch(exception e) { return "login";//返回登录页面 } } @requestmapping("/logout") public string logout(httpsession session) { subject subject = securityutils.getsubject(); subject.logout(); // session.removeattribute("user"); return "login"; } }
接下来就可以测试了,在没有登录的情况下,访问主页的时候会跳到登录的页面,而登录不同的用户也会随着用户所拥有的角色不同而显示不同的模块.
总结
以上所述是小编给大家介绍的springboot整合shiro的代码详解,希望对大家有所帮助
推荐阅读
-
详解spring cloud分布式整合zipkin的链路跟踪
-
Android Xutils3网络请求的封装详解及实例代码
-
SpringBoot+MyBatis简单数据访问应用的实例代码
-
消息队列 RabbitMQ 与 Spring 整合使用的实例代码
-
springboot整合rabbitmq的示例代码
-
SpringBoot+Websocket实现一个简单的网页聊天功能代码
-
springboot-controller的使用详解
-
springBoot整合CXF并实现用户名密码校验的方法
-
springboot整合cxf发布webservice以及调用的方法
-
编辑器Ueditor和SpringBoot 的整合方法