`
songchuanlu
  • 浏览: 32219 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

基于Spring框架Web应用程序Apache Shiro配置

阅读更多

一、在web.xml中添加shiro过滤器

 

<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>*.do</url-pattern>
	<dispatcher>REQUEST</dispatcher>
	<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<filter-mapping>
	<filter-name>shiroFilter</filter-name>
	<url-pattern>*.htm</url-pattern>
	<dispatcher>REQUEST</dispatcher>
	<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<filter-mapping>
	<filter-name>shiroFilter</filter-name>
	<url-pattern>*.json</url-pattern>
	<dispatcher>REQUEST</dispatcher>
	<dispatcher>FORWARD</dispatcher>
</filter-mapping>

 

二、在Spring的applicationContext.xml中添加shiro配置

 

1、sessionManger 会话管理

 

<bean id="sessionManager"
	class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
	<property name="globalSessionTimeout" value="3600000" />
	<property name="sessionValidationSchedulerEnabled" value="false" />
	<property name="deleteInvalidSessions" value="false" />
	<property name="sessionDAO">
		<bean class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
			<property name="activeSessionsCacheName" value="activeSessionCache" />
		</bean>
	</property>
</bean>

 

2、credentialsMatcher 密码加密

 

<bean id="credentialsMatcher"
	class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
	<property name="hashAlgorithmName" value="SHA-256" />
	<!-- true means hex encoded, false means base64 encoded -->
	<property name="storedCredentialsHexEncoded" value="false" />
</bean>

 

3、自定义Realm

 

<bean id="dbRealm" class="com.chuanlu.family.shiro.DbRealm">
	<property name="credentialsMatcher" ref="credentialsMatcher" />
	<property name="cacheManager" ref="cacheManager" />
</bean>

 

4、securityManager

 

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
	<property name="realms">
		<list>
			<ref local="dbRealm" />
		</list>
	</property>
	<!-- 此属性如果不配置,程序会创建默认Servlet容器会话 -->
	<property name="sessionManager" ref="sessionManager" />
	<!-- 此属性也可以配其他第三方缓存,如Memcached。如果不配置,则无法完成分布式集群,但不影响本地运行。-->
	<property name="cacheManager" ref="cacheManager" />
</bean>

 

5、shiroFilter

 

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
	<property name="securityManager" ref="securityManager" />
	<property name="loginUrl" value="/login.htm" />
	<property name="successUrl" value="/index.htm" />
	<property name="unauthorizedUrl" value="/login.htm" />
	<property name="filters">
		<util:map>
			<entry key="ssl">
				<bean class="org.apache.shiro.web.filter.authz.SslFilter">
					<property name="enabled" value="${ssl.enabled}" />
				</bean>
			</entry>
		</util:map>
	</property>
	<property name="filterChainDefinitions">
		<value>
			/login.htm = noSessionCreation, ssl[443]
			/login.do = anon
			/* = user
		</value>
	</property>
</bean>

 

6、shiro注解支持

 

<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

<bean
	class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
	depends-on="lifecycleBeanPostProcessor" />

<bean
	class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
	<property name="securityManager" ref="securityManager" />
</bean>

 

三、Ehcache配置

 

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<!--
    DiskStore configuration
    =======================

    The diskStore element is optional. To turn off disk store path creation, comment out the diskStore element below.

    Configure it if you have overflowToDisk or diskPersistent enabled for any cache.

    If it is not configured, and a cache is created which requires a disk store, a warning will be issued and java.io.tmpdir will automatically be used.

    diskStore has only one attribute - "path". It is the path to the directory where .data and .index files will be created.

    If the path is one of the following Java System Property it is replaced by its value in the running VM. For backward compatibility these should be specified without being enclosed in the ${token} replacement syntax.

    The following properties are translated:
    * user.home - User's home directory
    * user.dir - User's current working directory
    * java.io.tmpdir - Default temp file path
    * ehcache.disk.store.dir - A system property you would normally specify on the command line
      e.g. java -Dehcache.disk.store.dir=/u01/myapp/diskdir ...

    Subdirectories can be specified below the property e.g. java.io.tmpdir/one
    -->
    <diskStore path="java.io.tmpdir" />

<!--
    Mandatory Default Cache configuration. These settings will be applied to cachescreated programmtically using CacheManager.add(String cacheName).

    The defaultCache has an implicit name "default" which is a reserved cache name.
    -->
    <defaultCache maxElementsInMemory="10000" eternal="false"
        timeToIdleSeconds="120" timeToLiveSeconds="120"
        overflowToDisk="true" diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />

<!--
    Cache configuration
    ===================

    The following attributes are required.

    name:
    Sets the name of the cache. This is used to identify the cache. It must be unique.

    maxElementsInMemory:
    Sets the maximum number of objects that will be created in memory.  0 == no limit.

    maxElementsOnDisk:
    Sets the maximum number of objects that will be maintained in the DiskStore
    The default value is zero, meaning unlimited.

    eternal:
    Sets whether elements are eternal. If eternal,  timeouts are ignored and the
 element is never expired.

    overflowToDisk:
    Sets whether elements can overflow to disk when the memory store has reached the maxInMemory limit.

    The following attributes and elements are optional.

    timeToIdleSeconds:
    Sets the time to idle for an element before it expires.
    i.e. The maximum amount of time between accesses before an element expires
    Is only used if the element is not eternal.
    Optional attribute. A value of 0 means that an Element can idle for infinity.
    The default value is 0.

    timeToLiveSeconds:
    Sets the time to live for an element before it expires.
    i.e. The maximum time between creation time and when an element expires.
    Is only used if the element is not eternal.
    Optional attribute. A value of 0 means that and Element can live for infinity.
    The default value is 0.

    diskPersistent:
    Whether the disk store persists between restarts of the Virtual Machine.
    The default value is false.

    diskExpiryThreadIntervalSeconds:
    The number of seconds between runs of the disk expiry thread. The default value is 120 seconds.

    diskSpoolBufferSizeMB:
    This is the size to allocate the DiskStore for a spool buffer. Writes are made to this area and then asynchronously written to disk. The default size is 30MB.
    Each spool buffer is used only by its cache. If you get OutOfMemory errors consider lowering this value. To improve DiskStore performance consider increasing it. Trace level logging in the DiskStore will show if put back ups are occurring.

    clearOnFlush:
    whether the MemoryStore should be cleared when flush() is called on the cache.
    By default, this is true i.e. the MemoryStore is cleared.

    memoryStoreEvictionPolicy:
    Policy would be enforced upon reaching the maxElementsInMemory limit. Default
    policy is Least Recently Used (specified as LRU). Other policies available -
    First In First Out (specified as FIFO) and Less Frequently Used
    (specified as LFU)
-->
    <cache name="cacheManager" maxElementsInMemory="10000"
         eternal="false" overflowToDisk="false" 
         timeToIdleSeconds="60" 
        timeToLiveSeconds="120" memoryStoreEvictionPolicy="LFU" />
</ehcache>

 

三、自定义Realm类

 

/**
 * chuanlu
 */
package com.chuanlu.family.shiro;

import java.util.LinkedHashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.chuanlu.family.dao.UserDao;
import com.chuanlu.family.pojo.User;

/**
 * DbRealm
 *
 * @作者 宋陆
 * @日期 2013年10月5日 
 * @版本 1.0
 */
public class DbRealm extends AuthorizingRealm {

    @Resource
    private UserDao userDao;
    /**
     * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 授权信息
        Set<String> roleNames = new LinkedHashSet<String>();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
        return info;
    }

    /**
     * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 认证信息
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String userName = upToken.getUsername();
        SimpleAuthenticationInfo info = null;
        User user = userDao.getUserByUserName(userName);
        if (user != null) {
            String pwd = user.getPassword();
            String pwdSalt = user.getPwdSalt();
            info = new SimpleAuthenticationInfo(user.getUserId(), pwd.toCharArray(), getName());
            info.setCredentialsSalt(ByteSource.Util.bytes(pwdSalt));
        }
        return info;
    }

}

 

分享到:
评论

相关推荐

    spring mvc、apache shiro、mysql 框架搭建,基于maven构建

    Spring MVC是Spring框架的一个模块,专注于处理Web应用程序的请求和响应。它遵循模型-视图-控制器(MVC)设计模式,使得业务逻辑与表现层分离,提高了代码的可维护性和可测试性。Spring MVC通过DispatcherServlet...

    Apache Shiro 集成-spring

    总的来说,Apache Shiro与Spring的集成可以让我们在Spring的环境中充分利用Shiro的安全功能,为应用程序提供全面的安全保障。通过理解和实践这些知识点,开发者可以构建更加安全可靠的Java应用。

    基于maven构建 spring mvc + apache shiro + mysql 框架搭建

    这四个技术组件都是Java开发中的热门选择,它们各自在应用程序的不同层面提供强大的功能。 首先,Maven是一个项目管理和综合工具,它管理项目的依赖关系,自动化构建过程,如编译、测试、打包和部署等。通过在`pom....

    Apache Shiro教程

    Apache Shiro是一个强大的Java安全框架,它为应用程序提供了身份验证、授权、会话管理和加密等功能。这个教程将帮助你深入理解和有效地使用Shiro框架。在本文中,我们将详细探讨Shiro的核心概念、主要功能和常见用法...

    Spring Boot+Maven+Spring Data JPA+apache Shiro+Easyui实现通用用户权限管理系统

    1. **Spring Boot**: Spring Boot是Spring框架的简化版,它内置了常见的配置,如Tomcat服务器、Spring MVC、数据源等,使得开发者可以快速地搭建应用。通过“起步依赖”(Starter POMs)来引入所需的模块,如Spring ...

    让Apache Shiro保护你的应用

    5. **良好的集成性**:Shiro的API设计和架构模式使得与其他框架和应用的集成变得轻松,例如与Spring、Grails、Wicket等框架的无缝对接。 6. **强大的社区支持**:作为Apache软件基金会的一员,Shiro拥有活跃的开发者...

    Apache Shiro核心jar包:shiro-core-1.3.2

    Apache Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能。...使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。

    spring+springmvc+mybatis+shiro

    Spring MVC是Spring框架的一部分,专门用于构建Web应用程序。 2. **Spring MVC**:Spring MVC是Spring框架的一个模块,用于处理HTTP请求和响应。它提供了一种模型-视图-控制器(MVC)架构,帮助开发者将业务逻辑、...

    SpringBoot + Apache Shiro1.9.1 最新版本详细教程,基于RBAC角色访问、安全管理框架、用户角色权限

    4、优点:快速上手、全面支持验证、授权、加密和会话、灵活自定义设计、支持web环境、可以无缝集成spring等优点。可以用来用户验证、用户授权、用户session管理、安全加密等 5、基于RBAC五张表:用户表 tb_user、...

    Spring Shiro 学习系统 Spring-Shiro-training

    Spring框架则是一个广泛使用的Java企业级应用开发框架,涵盖了依赖注入、AOP(面向切面编程)、MVC(模型-视图-控制器)等多个领域。将Spring与Shiro结合,可以充分利用两者的优点,为应用程序提供全面的安全性支持...

    让Apache_Shiro保护你的应用.pdf

    Apache Shiro作为一款强大的安全框架,为Java应用程序提供了全面的安全解决方案。本文将深入探讨Apache Shiro的核心功能,以及如何利用它来保护你的应用。 #### Apache Shiro简介 Apache Shiro是一个开源的安全...

    Spring Boot+Apache Shiro+Spring MVC+MyBatis+Quartz+Druid DEMO

    - Spring MVC是Spring框架的一部分,用于构建Web应用,提供模型-视图-控制器模式的实现。 - 控制器:使用`@Controller`注解的类处理HTTP请求,转发到相应的服务层处理业务逻辑。 - 视图解析:配合视图技术(如JSP...

    将_Shiro_作为应用的权限基础_五:SpringMVC+Apache_Shiro+JPA(hibernate)整合配置

    ### 将Shiro作为应用的权限基础...综上所述,通过这些核心配置文件的详细解析,我们可以清晰地了解到如何将Apache Shiro与SpringMVC及JPA(hibernate)进行有效集成,为Web应用程序提供强大的权限管理和安全控制功能。

    springboot+springdatajpa+thymeleaf+shiro 的管理平台框架

    SpringBoot是Spring框架的简化版,旨在简化Spring应用程序的初始搭建以及开发过程。它预设了各种默认配置,如嵌入式Tomcat服务器、日志处理、自动配置等,使得开发者无需繁琐的配置即可快速启动项目。在本框架中,...

    Spring MVC+Mybatis+Ehcache+Apache Shiro+Bootstrap整合开发java仓库管理系统源码

    Spring MVC是Spring框架的一部分,用于构建Web应用程序。它提供了一个分层架构,包括控制器、服务、模型和视图。在这个仓库管理系统中,Spring MVC负责接收HTTP请求,调度控制器处理业务逻辑,然后将结果返回给用户...

    权限管理系统,基于Spring+SpringMvc+MiniJdbc+Shiro为架构的权限管理系统

    SpringMvc是Spring框架的一个模块,专为Web应用程序设计,实现了Model-View-Controller(MVC)设计模式,简化了前端控制器的实现。 其次,MiniJdbc是轻量级的数据库操作库,它简化了与JDBC的交互,提供了更简洁的...

    spring+springmvc+mybatis+shiro框架搭建

    **Spring框架**是Java企业级应用的核心框架,它提供了依赖注入(Dependency Injection, DI)和面向切面编程(Aspect-Oriented Programming, AOP)等功能,使得代码更加解耦,易于测试和维护。SpringMVC是Spring框架...

    Apache shiro权限控制基础配置代码

    Apache Shiro是一款强大的Java安全框架,它为应用程序提供了身份验证、授权、会话管理和加密等核心功能。在本文中,我们将深入探讨Apache Shiro的基础配置和代码实现,以帮助你理解如何有效地使用Shiro进行权限控制...

    shiro与spring web 项目集成.pdf

    Spring Web是基于Spring框架的Web应用开发解决方案,提供了对MVC设计模式的支持。将Shiro与Spring Web项目集成可以为Web应用带来安全功能,例如用户认证与授权。本指南将详细探讨Shiro与Spring Web项目集成的过程,...

    shiro-redis集成的spring的web项目

    本项目是一个将Apache Shiro与Redis缓存系统整合到Spring框架中的实例,旨在提升应用程序的安全性和性能。以下是对这个项目及其相关技术的详细解读。 **Apache Shiro** Apache Shiro是一个强大且易用的Java安全框架...

Global site tag (gtag.js) - Google Analytics