zoukankan      html  css  js  c++  java
  • springMVC集成 -- shiro(配置)

    备注:文中配置基本来自尚硅谷视频教程,也可自行参照shiro官方教程:http://shiro.apache.org/spring.html

    1、首先通过maven导入shiro相关依赖jar包,修改pom.xml文件

    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-all</artifactId>
        <version>1.3.2</version>
    </dependency>

    2、修改web.xml文件,添加如下内容

    <!-- Shiro Filter is defined in the spring application context: -->
        <!-- 
        1. 配置  Shiro 的 shiroFilter.  
        2. DelegatingFilterProxy 实际上是 Filter 的一个代理对象. 默认情况下, Spring 会到 IOC 容器中查找和 
        <filter-name> 对应的 filter bean. 也可以通过 targetBeanName 的初始化参数来配置 filter bean 的 id. 
        -->
        <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>

    3、修改spring配置文件applicationcontext.xml,配置如下bean:

    <!-- 1. 配置 SecurityManager  -->     
        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
            <property name="cacheManager" ref="cacheManager"/>
            <property name="authenticator" ref="authenticator"></property>
            <!-- 单个realm情况 -->
            <!-- <property name="realm" ref="myRealm" /> -->
            <!-- 多个realm情况 -->
            <property name="realms">
                <list>
                    <ref bean="jdbcRealm"/>
                    <ref bean="secondRealm"/>
                </list>
            </property>
            <!--shiro记住我功能的保存时间(秒)-->
            <property name="rememberMeManager.cookie.maxAge" value="10"></property>
        </bean>
    
      <!--  2. 配置 CacheManager. 
        2.1 需要加入 ehcache 的 jar 包及配置文件,此处shiro-all.jar已包含. 
        -->     
        <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
            <!-- Set a net.sf.ehcache.CacheManager instance here if you already have one.  If not, a new one
                 will be creaed with a default config:
                 <property name="cacheManager" ref="ehCacheManager"/> -->
            <!-- If you don't have a pre-built net.sf.ehcache.CacheManager instance to inject, but you want
                 a specific Ehcache configuration to be used, specify that here.  If you don't, a default
                 will be used.: -->
            <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/> 
        </bean>

      <!-- <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" /> -->

    <!-- 配置多Realm认证策略 -->
        <bean id="authenticator" 
            class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
            <property name="authenticationStrategy">
                <bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
            </property>
        </bean>
    
    
    <!-- 
            3. 配置 Realm 
            3.1 直接配置实现了 org.apache.shiro.realm.Realm 接口的 bean
        -->     
        <bean id="jdbcRealm" class="com.atguigu.shiro.realms.ShiroRealm">
            <!-- MD5加密 -->
            <property name="credentialsMatcher">
                <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                    <property name="hashAlgorithmName" value="MD5"></property>
                    <property name="hashIterations" value="1024"></property>
                </bean>
            </property>
        </bean>
        
        <bean id="secondRealm" class="com.atguigu.shiro.realms.SecondRealm">
            <!-- SHA1加密 -->
            <property name="credentialsMatcher">
                <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                    <property name="hashAlgorithmName" value="SHA1"></property>
                    <property name="hashIterations" value="1024"></property>
                </bean>
            </property>
        </bean>
    
    <!-- 4. 配置 LifecycleBeanPostProcessor. 可以自动的来调用配置在 Spring IOC 容器中 shiro bean 的生命周期方法.  -->       
        <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    
    <!--  5. 配置 ShiroFilter. 
        5.1 id 必须和 web.xml 文件中配置的 DelegatingFilterProxy 的 <filter-name> 一致.
                          若不一致, 则会抛出: NoSuchBeanDefinitionException. 因为 Shiro 会来 IOC 容器中查找和 <filter-name> 名字对应的 filter bean.
        -->     
        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
            <property name="securityManager" ref="securityManager"/>
            <property name="loginUrl" value="/login.jsp"/>
            <property name="successUrl" value="/list.jsp"/>
            <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
            
            <property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"></property>
            
            <!--  
                配置哪些页面需要受保护. 
                以及访问这些页面需要的权限. 
                1). anon 可以被匿名访问
                2). authc 必须认证(即登录)后才可能访问的页面. 
                3). logout 登出.
                4). roles 角色过滤器
            -->
            <!--  
            <property name="filterChainDefinitions">
                <value>
                    /login.jsp = anon
                    /shiro/login = anon
                    /shiro/logout = logout
                    
                    /user.jsp = roles[user]
                    /admin.jsp = roles[admin]
                    
                    # everything else requires authentication:
                    /** = authc
                </value>
            </property>
            -->
        </bean>

    4、修改springMVC配置文件spring-mvc.xml,添加如下内容

    <!--  
        启用 IOC 容器中使用 shiro 的注解. 但必须在配置了 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>

    5、添加ehcache.xml配置文件到classpath下:

    <ehcache>
    
        <!-- Sets the path to the directory where cache .data files are created.
    
             If the path is a Java System Property it is replaced by
             its value in the running VM.
    
             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 -->
        <diskStore path="java.io.tmpdir"/>
        
        <cache name="authorizationCache"
               eternal="false"
               timeToIdleSeconds="3600"
               timeToLiveSeconds="0"
               overflowToDisk="false"
               statistics="true">
        </cache>
    
        <cache name="authenticationCache"
               eternal="false"
               timeToIdleSeconds="3600"
               timeToLiveSeconds="0"
               overflowToDisk="false"
               statistics="true">
        </cache>
    
        <cache name="shiro-activeSessionCache"
               eternal="false"
               timeToIdleSeconds="3600"
               timeToLiveSeconds="0"
               overflowToDisk="false"
               statistics="true">
        </cache>
    
        <!--Default Cache configuration. These will applied to caches programmatically created through
            the CacheManager.
    
            The following attributes are required for defaultCache:
    
            maxInMemory       - Sets the maximum number of objects that will be created in memory
            eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                                is never expired.
            timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                                if the element is not eternal. Idle time is now - last accessed time
            timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                                if the element is not eternal. TTL is now - creation time
            overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                                has reached the maxInMemory limit.
    
            -->
        <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            />
    
        <!--Predefined caches.  Add your cache configuration settings here.
            If you do not have a configuration for your cache a WARNING will be issued when the
            CacheManager starts
    
            The following attributes are required for defaultCache:
    
            name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
            maxInMemory       - Sets the maximum number of objects that will be created in memory
            eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                                is never expired.
            timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                                if the element is not eternal. Idle time is now - last accessed time
            timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                                if the element is not eternal. TTL is now - creation time
            overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                                has reached the maxInMemory limit.
    
            -->
    
        <!-- Sample cache named sampleCache1
            This cache contains a maximum in memory of 10000 elements, and will expire
            an element if it is idle for more than 5 minutes and lives for more than
            10 minutes.
    
            If there are more than 10000 elements it will overflow to the
            disk cache, which in this configuration will go to wherever java.io.tmp is
            defined on your system. On a standard Linux system this will be /tmp"
            -->
        <cache name="sampleCache1"
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="300"
            timeToLiveSeconds="600"
            overflowToDisk="true"
            />
    
        <!-- Sample cache named sampleCache2
            This cache contains 1000 elements. Elements will always be held in memory.
            They are not expired. -->
        <cache name="sampleCache2"
            maxElementsInMemory="1000"
            eternal="true"
            timeToIdleSeconds="0"
            timeToLiveSeconds="0"
            overflowToDisk="false"
            /> -->
    
        <!-- Place configuration for your caches following -->
    
    </ehcache>

    此处附上realm的一个实现ShiroRealm.java:

    通常为了完成认证、授权,realm需继承自AuthorizingRealm

    package com.atguigu.shiro.realms;
    
    import java.util.HashSet;
    import java.util.Set;
    
    import org.apache.shiro.authc.AuthenticationException;
    import org.apache.shiro.authc.AuthenticationInfo;
    import org.apache.shiro.authc.AuthenticationToken;
    import org.apache.shiro.authc.LockedAccountException;
    import org.apache.shiro.authc.SimpleAuthenticationInfo;
    import org.apache.shiro.authc.UnknownAccountException;
    import org.apache.shiro.authc.UsernamePasswordToken;
    import org.apache.shiro.authz.AuthorizationInfo;
    import org.apache.shiro.authz.SimpleAuthorizationInfo;
    import org.apache.shiro.crypto.hash.SimpleHash;
    import org.apache.shiro.realm.AuthorizingRealm;
    import org.apache.shiro.subject.PrincipalCollection;
    import org.apache.shiro.util.ByteSource;
    
    public class ShiroRealm extends AuthorizingRealm {
    
    	@Override
    	protected AuthenticationInfo doGetAuthenticationInfo(
    			AuthenticationToken token) throws AuthenticationException {
    		System.out.println("[FirstRealm] doGetAuthenticationInfo");
    		
    		//1. 把 AuthenticationToken 转换为 UsernamePasswordToken 
    		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    		
    		//2. 从 UsernamePasswordToken 中来获取 username
    		String username = upToken.getUsername();
    		
    		//3. 调用数据库的方法, 从数据库中查询 username 对应的用户记录
    		System.out.println("从数据库中获取 username: " + username + " 所对应的用户信息.");
    		
    		//4. 若用户不存在, 则可以抛出 UnknownAccountException 异常
    		if("unknown".equals(username)){
    			throw new UnknownAccountException("用户不存在!");
    		}
    		
    		//5. 根据用户信息的情况, 决定是否需要抛出其他的 AuthenticationException 异常. 
    		if("monster".equals(username)){
    			throw new LockedAccountException("用户被锁定");
    		}
    		
    		//6. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo
    		//以下信息是从数据库中获取的.
    		//1). principal: 认证的实体信息. 可以是 username, 也可以是数据表对应的用户的实体类对象. 
    		Object principal = username;
    		//2). credentials: 密码. 
    		Object credentials = null; //"fc1709d0a95a6be30bc5926fdb7f22f4";
    		if("admin".equals(username)){
    			credentials = "038bdaf98f2037b31f1e75b5b4c9b26e";
    		}else if("user".equals(username)){
    			credentials = "098d2c478e9c11555ce2823231e02ec1";
    		}
    		
    		//3). realmName: 当前 realm 对象的 name. 调用父类的 getName() 方法即可
    		String realmName = getName();
    		//4). 盐值. 
    		ByteSource credentialsSalt = ByteSource.Util.bytes(username);
    		
    		SimpleAuthenticationInfo info = null; //new SimpleAuthenticationInfo(principal, credentials, realmName);
    		info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
    		return info;
    	}
    
    	public static void main(String[] args) {
    		String hashAlgorithmName = "MD5";
    		Object credentials = "123456";
    		Object salt = ByteSource.Util.bytes("user");;
    		int hashIterations = 1024;
    		
    		Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
    		System.out.println(result);
    	}
    
    	//授权会被 shiro 回调的方法
    	@Override
    	protected AuthorizationInfo doGetAuthorizationInfo(
    			PrincipalCollection principals) {
    		//1. 从 PrincipalCollection 中来获取登录用户的信息
    		Object principal = principals.getPrimaryPrincipal();
    		
    		//2. 利用登录的用户的信息来用户当前用户的角色或权限(可能需要查询数据库)
    		Set<String> roles = new HashSet<>();
    		roles.add("user");
    		if("admin".equals(principal)){
    			roles.add("admin");
    		}
    		
    		//3. 创建 SimpleAuthorizationInfo, 并设置其 reles 属性.
    		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
    		//也可通过info.addStringPermission(url);实现基于Permission的权限信息
    		//4. 返回 SimpleAuthorizationInfo 对象. 
    		return info;
    	}
    }
    

      

  • 相关阅读:
    原码、反码、补码,计算机中负数的表示
    [转]Vue 2.0——渐进式前端解决方案
    关于MySQL的tinyint(3)问题
    js对象的深拷贝及其的几种方法
    深入 js 深拷贝对象
    JS 数组克隆方法总结
    Undefined class constant 'MYSQL_ATTR_INIT_COMMAND'
    邮件措辞小计
    Forbidden You don't have permission to access / on this server PHP
    正则表达式
  • 原文地址:https://www.cnblogs.com/yinz/p/7306945.html
Copyright © 2011-2022 走看看