shiro的入门实例-shiro于spring的整合
shiro是一款java安全框架、简单而且可以满足实际的工作需要
第一步、导入maven依赖
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${org.apache.shiro.version}</version>
</dependency>
第二步、在项目中定义shiro的过滤器(shiro的实现主要是通过filter实现)
<!-- Shiro Security filter -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
第三步、创建一个Realm
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserBiz biz;
//验证用户信息,认证的实现
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String userno = (String) authenticationToken.getPrincipal();
String password = new String((char[]) authenticationToken.getCredentials());
Result<RcUser> result = biz.login(userno, password);
if (result.isStatus()) {
Session session = SecurityUtils.getSubject().getSession();
session.setAttribute(Constants.Token.RONCOO, userno);
RcUser user = result.getResultData();
return new SimpleAuthenticationInfo(user.getUserNo(), user.getPassword(), getName());
}
return null;
}
//验证用户的权限,实现认证
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
String userno = (String) principals.getPrimaryPrincipal();
Result<RcUser> result = biz.queryByUserNo(userno);
if(result.isStatus()){
Result<List<RcRole>> resultRole = biz.queryRoles(result.getResultData().getId());
if(resultRole.isStatus()){
//获取角色
HashSet<String> roles = new HashSet<String>();
for (RcRole rcRole : resultRole.getResultData()) {
roles.add(rcRole.getRoleValue());
}
System.out.println("角色:"+roles);
authorizationInfo.setRoles(roles);
//获取权限
Result<List<RcPermission>> resultPermission = biz.queryPermissions(resultRole.getResultData());
if(resultPermission.isStatus()){
HashSet<String> permissions = new HashSet<String>();
for (RcPermission rcPermission : resultPermission.getResultData()) {
permissions.add(rcPermission.getPermissionsValue());
}
System.out.println("权限:"+permissions);
authorizationInfo.setStringPermissions(permissions);
}
}
}
return authorizationInfo;
}
}
第四步、添加shiro配置
1、shiro缓存
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<ehcache updateCheck="false" name="shiroCache">
<!-- http://ehcache.org/ehcache.xml -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
</ehcache>
2、在spring的core配置文件中配置shiro
<description>Shiro安全配置</description>
<bean id="userRealm" class="com.roncoo.adminlte.controller.realm.UserRealm" />
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm" />
<property name="cacheManager" ref="shiroEhcacheManager" />
</bean>
<!-- Shiro 过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager" />
<!-- 身份认证失败,则跳转到登录页面的配置 -->
<property name="loginUrl" value="/login" />
<property name="successUrl" value="/certification" />
<property name="unauthorizedUrl" value="/error" />
<!-- Shiro连接约束配置,即过滤链的定义 -->
<property name="filterChainDefinitions">
<value>
/login = authc
/exit = anon
/admin/security/list=authcBasic,perms[admin:read]
/admin/security/save=authcBasic,perms[admin:insert]
/admin/security/update=authcBasic,perms[admin:update]
/admin/security/delete=authcBasic,perms[admin:delete]
</value>
</property>
</bean>
<!-- 用户授权信息Cache, 采用EhCache -->
<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache-shiro.xml" />
</bean>
<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
<!-- AOP式方法级权限检查 -->
<bean
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>
<bean
class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean>
第五步、shiro退出登录的实现
第一种方式
/**
* 退出登陆操作
*/
@RequestMapping(value = "/exit", method = RequestMethod.GET)
public String exit(RedirectAttributes redirectAttributes, HttpSession session) {
session.removeAttribute(Constants.Token.RONCOO);
SecurityUtils.getSubject().logout();
redirectAttributes.addFlashAttribute("msg", "您已经安全退出");
return redirect("/login");
}
第二种方式:在shiroFilter的约束配置中配置
<!-- Shiro连接约束配置,即过滤链的定义 -->
<property name="filterChainDefinitions">
<value>
/exit = logout
</value>
</property>
更多学习文章:http://www.roncoo.com/article/index
shiro是一款java安全框架、简单而且可以满足实际的工作需要
第一步、导入maven依赖
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${org.apache.shiro.version}</version>
</dependency>
第二步、在项目中定义shiro的过滤器(shiro的实现主要是通过filter实现)
<!-- Shiro Security filter --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> </filter-mapping>
第三步、创建一个Realm
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserBiz biz;
//验证用户信息,认证的实现
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String userno = (String) authenticationToken.getPrincipal();
String password = new String((char[]) authenticationToken.getCredentials());
Result<RcUser> result = biz.login(userno, password);
if (result.isStatus()) {
Session session = SecurityUtils.getSubject().getSession();
session.setAttribute(Constants.Token.RONCOO, userno);
RcUser user = result.getResultData();
return new SimpleAuthenticationInfo(user.getUserNo(), user.getPassword(), getName());
}
return null;
}
//验证用户的权限,实现认证
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
String userno = (String) principals.getPrimaryPrincipal();
Result<RcUser> result = biz.queryByUserNo(userno);
if(result.isStatus()){
Result<List<RcRole>> resultRole = biz.queryRoles(result.getResultData().getId());
if(resultRole.isStatus()){
//获取角色
HashSet<String> roles = new HashSet<String>();
for (RcRole rcRole : resultRole.getResultData()) {
roles.add(rcRole.getRoleValue());
}
System.out.println("角色:"+roles);
authorizationInfo.setRoles(roles);
//获取权限
Result<List<RcPermission>> resultPermission = biz.queryPermissions(resultRole.getResultData());
if(resultPermission.isStatus()){
HashSet<String> permissions = new HashSet<String>();
for (RcPermission rcPermission : resultPermission.getResultData()) {
permissions.add(rcPermission.getPermissionsValue());
}
System.out.println("权限:"+permissions);
authorizationInfo.setStringPermissions(permissions);
}
}
}
return authorizationInfo;
}
}
第四步、添加shiro配置
1、shiro缓存 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE xml> <ehcache updateCheck="false" name="shiroCache"> <!-- http://ehcache.org/ehcache.xml --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> </ehcache> 2、在spring的core配置文件中配置shiro <description>Shiro安全配置</description> <bean id="userRealm" class="com.roncoo.adminlte.controller.realm.UserRealm" /> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="userRealm" /> <property name="cacheManager" ref="shiroEhcacheManager" /> </bean> <!-- Shiro 过滤器 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- Shiro的核心安全接口,这个属性是必须的 --> <property name="securityManager" ref="securityManager" /> <!-- 身份认证失败,则跳转到登录页面的配置 --> <property name="loginUrl" value="/login" /> <property name="successUrl" value="/certification" /> <property name="unauthorizedUrl" value="/error" /> <!-- Shiro连接约束配置,即过滤链的定义 --> <property name="filterChainDefinitions"> <value> /login = authc /exit = anon /admin/security/list=authcBasic,perms[admin:read] /admin/security/save=authcBasic,perms[admin:insert] /admin/security/update=authcBasic,perms[admin:update] /admin/security/delete=authcBasic,perms[admin:delete] </value> </property> </bean> <!-- 用户授权信息Cache, 采用EhCache --> <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache-shiro.xml" /> </bean> <!-- 保证实现了Shiro内部lifecycle函数的bean执行 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> <!-- AOP式方法级权限检查 --> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"> <property name="proxyTargetClass" value="true" /> </bean> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager" /> </bean>
第五步、shiro退出登录的实现
第一种方式
/**
* 退出登陆操作
*/
@RequestMapping(value = "/exit", method = RequestMethod.GET)
public String exit(RedirectAttributes redirectAttributes, HttpSession session) {
session.removeAttribute(Constants.Token.RONCOO);
SecurityUtils.getSubject().logout();
redirectAttributes.addFlashAttribute("msg", "您已经安全退出");
return redirect("/login");
}
第二种方式:在shiroFilter的约束配置中配置
<!-- Shiro连接约束配置,即过滤链的定义 -->
<property name="filterChainDefinitions">
<value>
/exit = logout
</value>
</property>
shiro的入门实例-shiro于spring的整合的更多相关文章
- 权限框架 - shiro 简单入门实例
前面的帖子简单的介绍了基本的权限控制,可以说任何一个后台管理系统都是需要权限的 今天开始咱们来讲讲Shiro 首先引入基本的jar包 <!-- shiro --> <dependen ...
- Shiro learning - 入门学习 Shiro中的基础知识(1)
Shiro入门学习 一 .什么是Shiro? 看一下官网对于 what is Shiro ? 的解释 Apache Shiro (pronounced “shee-roh”, the Japanese ...
- Spring中IoC的入门实例
Spring中IoC的入门实例 Spring的模块化是很强的,各个功能模块都是独立的,我们可以选择的使用.这一章先从Spring的IoC开始.所谓IoC就是一个用XML来定义生成对象的模式,我们看看如 ...
- Shiro第四篇【Shiro与Spring整合、快速入门、Shiro过滤器、登陆认证】
Spring与Shiro整合 导入jar包 shiro-web的jar. shiro-spring的jar shiro-code的jar 快速入门 shiro也通过filter进行拦截.filter拦 ...
- Shiro之身份认证、与spring集成(入门级)
目录 1. Shro的概念 2. Shiro的简单身份认证实现 3. Shiro与spring对身份认证的实现 前言: Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在 JavaSE 环境 ...
- shiro实战系列(十五)之Spring集成Shiro
Shiro 的 JavaBean 兼容性使得它非常适合通过 Spring XML 或其他基于 Spring 的配置机制.Shiro 应用程序需要一个具 有单例 SecurityManager 实例的应 ...
- Spring boot整合shiro权限管理
Apache Shiro功能框架: Shiro聚焦与应用程序安全领域的四大基石:认证.授权.会话管理和保密. #,认证,也叫作登录,用于验证用户是不是他自己所说的那个人: #,授权,也就是访问控制,比 ...
- (39.2). Spring Boot Shiro权限管理【从零开始学Spring Boot】
(本节提供源代码,在最下面可以下载) (4). 集成Shiro 进行用户授权 在看此小节前,您可能需要先看: http://412887952-qq-com.iteye.com/blog/229973 ...
- Shiro learning - 入门案例(2)
Shiro小案例 在上篇Shiro入门学习中说到了Shiro可以完成认证,授权等流程.在学习认证流程之前,我们应该先入门一个Shiro小案例. 创建一个java maven项目 <?xml ve ...
随机推荐
- iOS子线程更新UI的两种方法
http://blog.csdn.net/libaineu2004/article/details/45368427 方法1:performSelectorOnMainThread[self perf ...
- 苹果应用商店AppStore审核中文指南 分类: ios相关 app相关 2015-07-27 15:33 84人阅读 评论(0) 收藏
目录 1. 条款与条件 2. 功能 3. 元数据.评级与排名 4. 位置 5. 推送通知 6. 游戏中心 7. 广告 8. 商标与商业外观 9. 媒体内容 10. 用户界面 11. 购买与货币 12. ...
- IOS开发-ObjC-Category的使用
在IOS移动App开发中,经常会出现以下情况:定义好了一个类,但后来需求升级或改变之后需要对这个类增加功能,这样的话往往需要修改类的结构,这样就会导致不能预期的问题产生,所以Obj-C提供了一种叫做C ...
- UVa 573 - The Snail
题目大意:有一只蜗牛位于深一个深度为h米的井底,它白天向上爬u米,晚上向下滑d米,由于疲劳原因,蜗牛白天爬的高度会比上一天少f%(总是相对于第一天),如果白天爬的高度小于0,那么这天它就不再向上爬,问 ...
- java系列--过滤器
在web.xml配置过滤器:过滤器一定要放在所以Servlet前面 过滤器的生命周期: 过滤器的应用: 1.编码格式 2.权限验证 3.数据库关闭
- Nodejs之发送邮件nodemailer
nodejs邮件模块nodemailer的使用说明 1.介绍 nodemailer是node的一个发送邮件的组件,其功能相当强大,普通邮件,传送附件,邮件加密等等都能实现,而且操作也十分方便. nod ...
- iOS 程序测试、程序优化、提交前检测
1. 数据显示如果是数值要考虑到0的情况 2. 数据变化对前一个页面及相关页面的影响,也即数据同步问题.如果是有其它设备改变数据,那数据请求就应该在willappear(视图将要显示事件)进行请求,以 ...
- 三 APPIUM Android自动化 测试初体验
1.创建一个maven项目 成功新建工程: 编辑pom.xml,在<dependencies></dependencies>下添加appium相关依赖: <depende ...
- DevExpress控件学习总结2(转)
1.TextEditor(barEditItem)取文本string editValue = barEditItem1.EditValue.ToString(); //错误,返回null string ...
- 在asp.net中使用ajax记录
一.问题描述 ajax在mvc中使用频繁,比如cms中的评论功能,但由于涉及到前后端开发,日久容易忘,在此做下记录. 二.内容 控制器中代码示例: /// <summary> /// 在文 ...