Shiro的使用与配置实战

1.关于Shiro在Spring中的配置1.直接在HIbernate中使用Ehcache的配置

1.关于Shiro在Spring中的配置

1.直接在HIbernate中使用Ehcache的配置


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"  
 xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring" 
 xmlns:task="http://www.springframework.org/schema/task"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd   
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
    http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring 
    http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd 
    http://www.springframework.org/schema/task  
http://www.springframework.org/schema/task/spring-task-4.1.xsd">  

    <context:annotation-config/>
    <!-- 启动对@AspectJ注解的支持,为了事务处理和Aop处理日志 -->  
	<aop:aspectj-autoproxy />

	<context:component-scan base-package="com.jay.platform" />
	<!-- 读取Properties文件配置信息 -->
	<context:property-placeholder location="classpath:jdbc.properties"
		ignore-unresolvable="true" />
		
	<!-- 数据库连接池,DBCP -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="timeBetweenEvictionRunsMillis">
			<value>3600000</value><!--1 hours -->
		</property>
		<property name="minEvictableIdleTimeMillis">
			<value>28800000</value><!--8 hours -->
		</property>
	</bean>
	
    
   <!-- Hibernate4中使用以下配置方式 -->
   <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
        <property name="dataSource" ref="dataSource" />
       <!--  采用注解形式配置对象关系映射信息 -->  
        <property name="packagesToScan"> 
              <list> 
                   <value>com.jay.platform.*</value> 
              </list> 
        </property>
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>  
                <prop key="hibernate.show_sql">true</prop>  
                <prop key="hibernate.format_sql">true</prop>  
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>   
               <!--  最大抓取深度,如果为0,则关闭默认的外连接抓取。建议值为0-3   -->
                <prop key="hibernate.max_fetch_depth">3</prop>  
               <!--  用于生成有助于调试的注释信息,默认为关闭   -->
                <prop key="hibernate.use_sql_comments">true</prop>
                <prop key="connection.autocommit">true</prop>  
                
                <!-- Hibernate配置EhCache 用作二级缓存 -->
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop> 
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="cache.provider_configuration_file_resource_path">ehcache.xml</prop>
            </props>  
        </property>  
            
    </bean>  
    
   <!-- 配置事务管理器 -->
    <bean id="txManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
 
    <!-- 配置事务异常封装-->
    <bean id="persistenceExceptionTranslationPostProcessor"
          class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
 
    <!-- 声明式容器事务管理-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="create*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="merge*" propagation="REQUIRED" />
            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="put*" propagation="REQUIRED" />
            <tx:method name="use*" propagation="REQUIRED"/>
            <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到-->
            <tx:method name="get*" propagation="REQUIRED" read-only="true" />
            <tx:method name="count*" propagation="REQUIRED" read-only="true" />
            <tx:method name="find*" propagation="REQUIRED" read-only="true" />
            <tx:method name="list*" propagation="REQUIRED" read-only="true" />
            <tx:method name="*" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <aop:config expose-proxy="true">
        <!-- 只对业务逻辑层实施事务 -->
        <aop:pointcut id="txPointcut" expression="execution(* com.jay.platform.service..*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
    
    
    <!-- Shiro相关配置 -->
    <bean id="authorityFilter" class="com.jay.platform.filter.AuthorityFilter" />
    <bean id="userRealm" class="com.jay.platform.shiro.UserRealm" />
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="userRealm"></property>
    </bean>

    <!-- logout后返回的页面 -->
    <bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
     <property name="redirectUrl" value="/index.htm" />
     </bean>
    
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"></property>
        <!-- 登录Url -->
        <property name="loginUrl" value="/index.htm"></property>
        <!-- 未授权要跳转到的url -->
        <property name="unauthorizedUrl" value="/index.htm"></property> 
        <!-- 配置的过滤器 -->
        <property name="filters">
            <map>
                <entry key="authc" value-ref="authorityFilter" /> 
                <entry key="logout" value-ref="logoutFilter" />
            </map>
        </property>
        <property name="filterChainDefinitions">
            <value>
                /resources/*/**=anon
                /index.htm=anon
                /getCode.htm=anon
                
                /**=authc
               /home.htm=authc
             <!--   /system/user/**= perms["sys:user:add,sys:user:update"] -->
            </value>
        </property>
    </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">
    </bean>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
    
    <!-- Spring MVC的统一异常处理 -->
    <bean id="exceptionResolver" class="com.jay.platform.exception.handler.ExceptionHandler"/>  
    
     
     <!-- 引入定时器框架Quartz的配置 -->
    <!-- <import resource="quartz-config.xml"/> -->

    <!-- 通过注解的形式,执行定时器 -->
 <!-- 配置Spring定时器,扫描注解 -->
    <!-- <task:annotation-driven/>  -->
    
    
</beans>


2.在Shiro中使用了Ehcache的配置

<!-- shiro start -->
 <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
 <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
     <property name="cacheManagerConfigFile"
         value="classpath:ehcache.xml" />
 </bean>
 <bean id="credentialsMatcher"
     class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
     <property name="hashAlgorithmName" value="SHA-256" />
 </bean>
 <bean id="iniRealm" class="com.boonya.shiro.security.CurrentIniRealm">
     <constructor-arg type="java.lang.String" value="classpath:shiro.ini" />
     <property name="credentialsMatcher" ref="credentialsMatcher" />
 </bean>
 <bean id="userRealm" class="com.boonya.shiro.security.UserRealm" />
 <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
     <property name="realms">
         <list>
             <ref bean="iniRealm" />
             <ref bean="userRealm" />
         </list>
     </property>
     <property name="cacheManager" ref="cacheManager" />
 </bean>
 <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
     <property name="securityManager" ref="securityManager" />
     <property name="loginUrl" value="/login" />
     <property name="successUrl" value="/maps/main.html"></property>
     <property name="unauthorizedUrl" value="/unauthorized"></property>
     <property name="filters">
         <util:map>
             <entry key="anAlias">
                 <bean
                     class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter" />
             </entry>
         </util:map>
     </property>
     <property name="filterChainDefinitions">
         <value>
             /unauthorized=anon
             /validate/code*=anon
             /login/**=anon
             /image/**=anon
             /js/**=anon
             /css/**=anon
             /common/**=anon
             /index.htm* = anon
             /maps/**=authc            
        </value>
     </property>
 </bean>


3.web.xml中shiroFilter配置

<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


4.关于Shiro配置的过滤属性的说明:

securityManager:这个属性是必须的

loginUrl :没有登录的用户请求需要登录的页面时自动跳转到登录页面,不是必须的属性,不输入地址的话会自动寻找项目web项目的根目录下的”/login.jsp”页面。

successUrl :登录成功默认跳转页面,不配置则跳转至”/”。如果登陆前点击的一个需要登录的页面,则在登录自动跳转到那个需要登录的页面。不跳转到此。

unauthorizedUrl :没有权限默认跳转的页面。

===============其权限过滤器及配置释义=======================

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
anon   org.apache.shiro.web.filter.authc.AnonymousFilter
 
authc  org.apache.shiro.web.filter.authc.FormAuthenticationFilter
 
authcBasic org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
 
perms  org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter
 
port   org.apache.shiro.web.filter.authz.PortFilter
 
rest   org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
 
roles  org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
 
ssl    org.apache.shiro.web.filter.authz.SslFilter
 
user   org.apache.shiro.web.filter.authc.UserFilter
 
logout org.apache.shiro.web.filter.authc.LogoutFilter

anon:例子/admins/**=anon 没有参数,表示可以匿名使用。

authc:例如/admins/user/**=authc表示需要认证(登录)才能使用,没有参数

roles例子/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,例如admins/user/**=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。

perms例子/admins/user/**=perms[user:add:*],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,例如/admins/user/**=perms["user:add:*,user:modify:*"]当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。

rest:例子/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[user:method] ,其中methodpostgetdelete等。

port:例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议httphttps等,serverName是你访问的host,8081url配置里port的端口,queryString

是你访问的url里的?后面的参数。

authcBasic例如/admins/user/**=authcBasic没有参数表示httpBasic认证

ssl:例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https

user:例如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查

注:anonauthcBasicauchcuser是认证过滤器,

permsrolessslrestport是授权过滤器



2.参考Shiro框架权限实践


.spring集成shiro

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3.   
  4. <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  6.          version="2.5">  
  7.     <welcome-file-list>  
  8.         <welcome-file>login.jsp</welcome-file>  
  9.     </welcome-file-list>  
  10.       
  11. <!-- 加载spring的配置****begin -->  
  12.     <listener>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值