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的整合的更多相关文章

  1. 权限框架 - shiro 简单入门实例

    前面的帖子简单的介绍了基本的权限控制,可以说任何一个后台管理系统都是需要权限的 今天开始咱们来讲讲Shiro 首先引入基本的jar包 <!-- shiro --> <dependen ...

  2. Shiro learning - 入门学习 Shiro中的基础知识(1)

    Shiro入门学习 一 .什么是Shiro? 看一下官网对于 what is Shiro ? 的解释 Apache Shiro (pronounced “shee-roh”, the Japanese ...

  3. Spring中IoC的入门实例

    Spring中IoC的入门实例 Spring的模块化是很强的,各个功能模块都是独立的,我们可以选择的使用.这一章先从Spring的IoC开始.所谓IoC就是一个用XML来定义生成对象的模式,我们看看如 ...

  4. Shiro第四篇【Shiro与Spring整合、快速入门、Shiro过滤器、登陆认证】

    Spring与Shiro整合 导入jar包 shiro-web的jar. shiro-spring的jar shiro-code的jar 快速入门 shiro也通过filter进行拦截.filter拦 ...

  5. Shiro之身份认证、与spring集成(入门级)

    目录 1. Shro的概念 2. Shiro的简单身份认证实现 3. Shiro与spring对身份认证的实现 前言: Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在 JavaSE 环境 ...

  6. shiro实战系列(十五)之Spring集成Shiro

    Shiro 的 JavaBean 兼容性使得它非常适合通过 Spring XML 或其他基于 Spring 的配置机制.Shiro 应用程序需要一个具 有单例 SecurityManager 实例的应 ...

  7. Spring boot整合shiro权限管理

    Apache Shiro功能框架: Shiro聚焦与应用程序安全领域的四大基石:认证.授权.会话管理和保密. #,认证,也叫作登录,用于验证用户是不是他自己所说的那个人: #,授权,也就是访问控制,比 ...

  8. (39.2). Spring Boot Shiro权限管理【从零开始学Spring Boot】

    (本节提供源代码,在最下面可以下载) (4). 集成Shiro 进行用户授权 在看此小节前,您可能需要先看: http://412887952-qq-com.iteye.com/blog/229973 ...

  9. Shiro learning - 入门案例(2)

    Shiro小案例 在上篇Shiro入门学习中说到了Shiro可以完成认证,授权等流程.在学习认证流程之前,我们应该先入门一个Shiro小案例. 创建一个java maven项目 <?xml ve ...

随机推荐

  1. NULL、nil、Nil、NSNull的区别

    标志 值 含义 NULL (void *)0 C指针的字面零值 nil (id)0 Objecve-C对象的字面零值 Nil (Class)0 Objecve-C类的字面零值 NSNull [NSNu ...

  2. js局部变量,参数

    作者:zccst 所有函数的参数都是按值传递的.也就是说,把函数外部的值复制给函数内部的参数,就和把值从一个变量复制到另一个变量一样.基本类型值的传递如同基本类型变量的赋值一样.而引用类型值的传递,则 ...

  3. RFID射频卡超市购物结算系统问题记录--写入卡片时,后台php无法操作数据库

    后台管理人员要给每件商品贴上RF卡作为唯一标识,所以要先给对应的RFID卡中写入响应的信息,我这里为了便于模拟演示只写入商品编号,价格,名称这几个字段,然后要把已经写入的商品上传后台,由后台写入数据库 ...

  4. 在PHP语言中使用JSON

      目前,JSON已经成为最流行的数据交换格式之一,各大网站的API几乎都支持它. 我写过一篇<数据类型和JSON格式>,探讨它的设计思想.今天,我想总结一下PHP语言对它的支持,这是开发 ...

  5. 使用spol导出exce

    sqlplus 能生产xls的excel文件 connect / as sysdba; SET NEWPAGE 0 SET SPACE 0 SET LINESIZE 80 SET PAGESIZE 0 ...

  6. APK的反编译

    有秘密的地方就有见不得光的东西,我讨厌这些,所以对于某一个XX圈APP极其反感,感觉就像一个色情网站 一.ApkTool的使用 看了几个教程,自己下载的好像总是不完整,下载包解压后一个没有aapt.e ...

  7. yum命令被锁 Existing lock /var/run/yum.pid

    有时使用yum命令,不知怎会回事就提示: Existing lock /var/run/yum.pid: another copy is running as... 感觉也没操作什么错误的事情. 此时 ...

  8. UVa 129 困难的串

    https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem& ...

  9. sklearn数据预处理-scale

    对数据按列属性进行scale处理后,每列的数据均值变成0,标准差变为1.可通过下面的例子加深理解: from sklearn import preprocessing import numpy as ...

  10. JS 响应式编程

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script ...