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. ARM裸机开发中内存管理库RT_HEAP的使用

    在使用arm芯片进行裸机开发的时候,很多时候都需要内存管理的功能,我们可以使用自己写的内存管理程序,也可以直接使用标准库,不过我一般比较喜欢标准库,速度快,今天就来说说在C语言环境下怎么样进行内存的动 ...

  2. 原来在ARC下还有这么多不同?!

    1.ARC空声明变量 使用ARC的另一个优势是所有未初始化的变量默认都是"空值化"的.这意味着像下面这样的声明使用ARC编译后指向的是空值(nil): NSObject myObj ...

  3. iOS开发——发短信,邮件

    在IOS开发中,有时候我们会需要用到邮件发送的功能.比如,接收用户反馈和程序崩溃通知等等,这个功能是很常用的.在苹果系统中,如果彼此的手机都是iOS设备,并且开通了iMessage功能,那么彼此之间的 ...

  4. iOS 将NSArray、NSDictionary转换为JSON格式进行网络传输

    http://blog.csdn.net/worldzhy/article/details/49982491 将NSArray.NSDictionary转换为JSON格式进行网络传输,是经常用到的,但 ...

  5. Qt编译Oracle OCI驱动

    最近使用qt开发了一个访问数据库的工具, 默认使用ODBC驱动注入的方式,后来发现Oracle中ODBC驱动注入经常失败. 后来就想直接使用OCI方式访问,而默认情况下Qt只有Sqlite和ODBC驱 ...

  6. Vector类

    /* * Vector的特有功能 * * Vector出现较早,比集合更早出现 * * 1:添加功能 * public void addElement(Object obj);//用add()替代 * ...

  7. PHP的高并发和大数据处理

    收集前人的经验.加速学习,解决工作中的难题. 一.代码优化(包括sql语句的优化), 合理的使用索引,避免整表查询.二.日常海量数据处理我用文件缓存,文件缓存分两种,第一种是最常见的生成html静太文 ...

  8. python实现断点续传下载文件

    最近的任务里有一个功能是要我从日志服务器实时跟新日志到本地,日志在不断新增内容就需要我隔一段时间从上次下载的位置继续下载,并写入本地文件上次写完的位置后面. headers = {'Range': ' ...

  9. 理解Action,Service和Dao功能(转)

    真正理解.区分Action,Service和Dao功能   在不分层的系统里,我们可以将所有的代码都写到一个地方,比如struts的Action类.在这里,我们不仅要处理页面逻辑,还要做业务逻辑,还要 ...

  10. Recovering a WiredTiger collection from a corrupt MongoDB installation

    Reference: http://www.alexbevi.com/blog/2016/02/10/recovering-a-wiredtiger-collection-from-a-corrupt ...