Shiro与Spring集成

1、shiro相关jar包的maven依赖。

<!-- Spring Shiro -->
<dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-core</artifactId>
   <version>1.2.3</version>
</dependency>
<dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-web</artifactId>
   <version>1.2.3</version>
</dependency>
<dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-spring</artifactId>
   <version>1.2.3</version>
</dependency>
<dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-ehcache</artifactId>
   <version>1.2.3</version>
</dependency>
<dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-quartz</artifactId>
   <version>1.2.3</version>
</dependency>

2、web.xml中shiro的相关配置。

1)引入shiro的配置文件applicationContext-shiro.xml。

<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>
       classpath*:/applicationContext-shiro.xml
       </param-value>
</context-param>


2)在web.xml中配置shiroFilter过滤器。

<!-- 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>/*</url-pattern>
</filter-mapping>

web.xml 文件配置中配置注意的问题点:

1.如果你的项目动态请求都是*.action *.do 等结尾,那么拦截配置就直接配置为<url-pattern>*.action</url-pattern> 或者<url-pattern>*.do</url-pattern> 

2.过滤器配置的顺序,过滤器最好配置的位置是在org.springframework.web.filter.CharacterEncodingFilter 之后,就是处理好字符集就是Shiro的过滤器。


3、Shiro相关配置applicationContext-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
   <description>Spring-Shiro</description>

   <!-- 配置Shiro Filter过滤器 -->
   <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
      <!-- 将shiro安全管理器注入ShiroFilter中 -->
      <property name="securityManager" ref="securityManager" />

      <!-- 配置登录URL地址 -->
      <property name="loginUrl" value="/login.html" />

      <!-- 配置登录成功后访问地址 -->
      <!-- <property name="successUrl" value="/index.html" /> -->

      <!-- 配置不授权URL地址 -->
      <property name="unauthorizedUrl" value="/error/403.html" />

      <!-- 基本系统级别权限配置 -->
      <!-- filterChainDefinitions的配置顺序为自上而下,以最上面的为准 -->
      <!-- anon表示可匿名使用,可以理解为匿名用户或游客,即非登录下可访问 -->
      <!-- authc表示需认证才能使用,即登录后才可使用 -->
      <property name="filterChainDefinitions">
         <value>
            /css/** = anon
            /images/** = anon
            /js/** = anon
            /login.html = anon
            /onLogin.html = anon
            /logout.html = anon
            /druid/** = anon
            /attached/** = anon
            /** = authc
         </value>
      </property>
   </bean>

   <!-- 基于Form表单的身份验证过滤器 -->
   <!--<bean id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
      <property name="usernameParam" value="username"/>
      <property name="passwordParam" value="password"/>
      <property name="loginUrl" value="/login.jsp"/>
      <property name="rememberMeParam" value="rememberMe"/>
   </bean>-->

   <!-- 配置Shiro 安全管理器 -->
   <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
      <!-- 将自定义shiro域注入Shiro安全管理器 -->
      <property name="realm" ref="shiroRealm" />
      <!-- 将缓存管理器注入Shiro安全管理器 -->
      <property name="cacheManager" ref="ehCacheManager" />
      <!-- 将会话管理器注入Shiro安全管理器-->
      <property name="sessionManager" ref="sessionManager"/>
      <!-- 将rememberMe管理器注入Shiro安全管理器 -->
      <property name="rememberMeManager" ref="rememberMeManager"/>
   </bean>

   <!-- 配置Shiro 会话管理器 -->
   <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
      <property name="globalSessionTimeout" value="1800000"/>
      <property name="deleteInvalidSessions" value="true"/>
      <property name="sessionValidationSchedulerEnabled" value="true"/>
      <!-- 注入会话验证调度器 -->
      <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
      <!-- 注入会话DAO -->
      <property name="sessionDAO" ref="sessionDAO"/>
      <!-- 开启会话Cookie -->
      <property name="sessionIdCookieEnabled" value="true"/>
      <!-- 注入会话Cookie模板 -->
      <property name="sessionIdCookie" ref="sessionIdCookie"/>
   </bean>

   <!-- 装载自定义的Shiro Realm(域) -->
   <bean id="shiroRealm" class="com.gcmobile.console.security.ShiroRealm" >
      <!-- 注入凭证匹配器 -->
      <property name="credentialsMatcher" ref="credentialsMatcher"/>
      <property name="cachingEnabled" value="true"/>
      <property name="authenticationCachingEnabled" value="true"/>
      <property name="authenticationCacheName" value="authenticationCache"/>
      <property name="authorizationCachingEnabled" value="true"/>
      <property name="authorizationCacheName" value="authorizationCache"/>
   </bean>

   <!-- 配置Shiro 缓存管理器,此处采用EhCacheManager实现 -->
   <bean id="ehCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
      <!-- 引入缓存配置文件 -->
      <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml" />
   </bean>

   <!-- 凭证匹配器 -->
   <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
      <property name="hashAlgorithmName" value="md5" />
      <property name="hashIterations" value="2"/>
      <property name="storedCredentialsHexEncoded" value="true"/>
   </bean>

   <!-- 会话Cookie模板 -->
   <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
      <constructor-arg value="sid"/>
      <property name="httpOnly" value="true"/>
      <property name="maxAge" value="180000"/>
   </bean>
   <!-- rememberMeCookie模板 -->
   <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
      <constructor-arg value="rememberMe"/>
      <property name="httpOnly" value="true"/>
      <property name="maxAge" value="2592000"/><!-- 30天 -->
   </bean>

   <!-- 会话ID生成器 -->
   <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>

   <!-- 会话DAO -->
   <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
      <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
      <!-- 注入会话ID生成器 -->
      <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
   </bean>

   <!-- 会话验证调度器 -->
   <bean id="sessionValidationScheduler"  class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">
      <property name="sessionValidationInterval" value="1800000"/>
      <!-- 注入会话管理器 -->
      <property name="sessionManager" ref="sessionManager"/>
   </bean>

   <!-- rememberMe管理器 -->
   <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
      <property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}"/>
      <!-- 注入rememberMe的cookie -->
      <property name="cookie" ref="rememberMeCookie"/>
   </bean>

   <!-- 静态注入,相当于调用SecurityUtils.setSecurityManager(securityManager) -->
   <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
      <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager" />
      <property name="arguments" ref="securityManager" />
   </bean>

   <!-- Shiro生命周期处理器,保证实现了Shiro内部lifecycle函数的bean执行 -->
   <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

   <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>
</beans>

4、Ehcache相关配置ehcache-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="shiroCache">
   <diskStore path="java.io.tmpdir"/>
   
   <defaultCache
      maxElementsInMemory="10000"
      eternal="false"
      timeToIdleSeconds="120"
      timeToLiveSeconds="120"
      overflowToDisk="false"
      diskPersistent="false"
      diskExpiryThreadIntervalSeconds="120" />
</ehcache>

5、自定义ShiroRealm实现

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.gcmobile.console.system.entity.User;
import com.gcmobile.console.system.mapper.UserMapper;

/**
 * Shiro自定义域,实现认证、授权
 */
public class ShiroRealm extends AuthorizingRealm{
	
   @Autowired
   private UserMapper userMapper;  // 用户表mapper接口

   public ShiroRealm() {
      setAuthenticationTokenClass(UsernamePasswordToken.class);
   }

   /**
    * Shiro认证方法,实现登录认证
    * @param authenticationToken
    * @return
     */
   @Override
   protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
      // 获取usernamePasswordToken里面的用户名、密码
      UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
      // 根据用户名查询用户信息
      User user = userMapper.selectByUserName(usernamePasswordToken.getUsername());
      if (user == null) {
         throw new UnknownAccountException("Unknown username [" + usernamePasswordToken.getUsername() + "]");
      }
      if (!user.getStatus().equals(0)) {
         throw new DisabledAccountException("Disabled account [" + usernamePasswordToken.getUsername() + "]");
      }
      // 将用户信息保存至ShiroUser实体类
      ShiroUser shiroUser = new ShiroUser(user.getId(), user.getUserName());
      shiroUser.setUserName(user.getName());
      shiroUser.setUserId(user.getId());
      // 将shiroUser用户信息及查出的密码与usernamePasswordToken中的用户名、密码进行比较,并将shiroUser实体类保存至缓存中
      return new SimpleAuthenticationInfo(shiroUser, user.getPassword(), getName());
   }

   /**
    * Shiro授权方法,实现权限控制
    * @param principalCollection
    * @return
     */
   @Override
   protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
      // 取出当前已登录的用户信息
      ShiroUser shiroUser = (ShiroUser) principalCollection.getPrimaryPrincipal();
      SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
      System.out.print("=============");
      // 将当前用户的角色放入授权信息类的角色组中
      info.addRoles(userMapper.queryRolesByUserId(shiroUser.getUserId()));
      // 将当前用户的权限放入授权信息类的权限组中
      info.addStringPermissions(userMapper.queryPermissionsByUserId(shiroUser.getUserId()));
      return info;
   }
}
 
6、ShiroUser类,自定义Authentication对象,使得Subject除了携带用户登录名外还可以携带更多信息 

import java.io.Serializable;

/**
 * 自定义Authentication对象,使得Subject除了携带用户的登录名外还可以携带更多信息.
 */
public class ShiroUser implements Serializable {
   private static final long serialVersionUID = 4999382582432113545L;
   private Integer userId;
   private String userName;
   private String name;

   public ShiroUser() {}

   public ShiroUser(Integer userId, String userName) {
      this.userId = userId;
      this.userName = userName;
   }

   public Integer getUserId() {
      return userId;
   }

   public void setUserId(Integer userId) {
      this.userId = userId;
   }

   public String getUserName() {
      return userName;
   }

   public void setUserName(String userName) {
      this.userName = userName;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}
 
7、登录调用Shiro进行认证

// 如果已登录,则先退出登录
SecurityUtils.getSubject().logout();
// 实例化一个subject实体
Subject subject = SecurityUtils.getSubject();
// UsernamePasswordToken封装用户名、密码
UsernamePasswordToken token = new UsernamePasswordToken(username, MD5.toMD5(password));
// 开始登录认证
subject.login(token);



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值