Shiro集成Spring

1、新建web项目

2、导入jar包

在这里插入图片描述

3、编写配置文件

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <!-- 配置Spring两个标签:上下文参数和监听器 -->
  <!-- 上下文参数 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- 监听器 -->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  
  <!-- 配置Springmvc两个标签, 前端控制器he字符编码过滤器-->
  <!-- 前端控制器 -->
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<!-- 初始化配置springmvc路径 -->
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:springmvc.xml</param-value>
  	</init-param>
  	<!-- 自启动 -->
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- 字符编码过滤器 -->
  <filter>
  	<filter-name>encoding</filter-name>
  	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>utf-8</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>encoding</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
   <!-- Shiro Filter is defined in the spring application context: -->
    <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-app>

applicationContext.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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                       http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 注解扫描 -->
    <context:component-scan base-package="com.liang.service"></context:component-scan>    
    <!--加载属性文件 -->
   	<!-- =========================================================
         Shiro Core Components - Not Spring Specific
         ========================================================= -->
    <!-- 1.配置 SecurityManager-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="cacheManager"/>
        <!-- Single realm app.  If you have multiple realms, use the 'realms' property instead. -->
        <property name="sessionMode" value="native"/>
        <!-- 加载认证策略  -->
        <property name="authenticator" ref="authenticator"/>
        <!-- 加载realms,也可以配置在authenticator中 -->
        <property name="realms">
			<list>
				<ref bean="jdbcRealm"/>
				<ref bean="secondRealm"/>
			</list>
		</property>
		<!-- 记住我的时间 -->
		<property name="rememberMeManager.cookie.maxAge" value="10"></property>
    </bean>

    
    <!-- 2.配置 CacheManager,需要导入ehcache.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="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
		<property name="authenticationStrategy">
			<!-- 所有realm全部匹配成功策略 -->
			<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
		</property>
	</bean>
	<!-- 3.配置Realms,可以配置多个 -->
    <bean id="jdbcRealm" class="com.liang.realm.ShiroRealm">
        <property name="credentialsMatcher">
        	<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        		<property name="hashAlgorithmName" value="MD5"></property>
        		<!-- 加密次数 -->
        		<property name="hashIterations" value="10"></property>
        	</bean>
        </property>
    </bean>
    <bean id="secondRealm" class="com.liang.realm.SecondRealm">
        <property name="credentialsMatcher">
        	<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        		<property name="hashAlgorithmName" value="SHA1"></property>
        		<!-- 加密次数 -->
        		<property name="hashIterations" value="10"></property>
        	</bean>
        </property>
    </bean>

    <!-- =========================================================
         Shiro Spring-specific integration
         ========================================================= -->
   	<!-- 4.配置LifecycleBeanPostProcessor,可以自动的来调用配置在String IOC 容器中shiro bean 的生命周期方法 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

   	<!-- 5.启用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>

    
	
   	<!-- 6.配置ShiroFilter.id必须和web.xml文件中配置的DelegatingFilterProxy的<filter-name>保持一致  -->
    <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>
       <!--  
        	配置哪些页面需要受保护,以及访问这些页面需要的权限
        	anon可以被匿名访问
        	authc必须认证之后才能被访问,即登录后
        	logout 登出过滤器
        	roles角色过滤器
         -->
         <!--   
        <property name="filterChainDefinitions">
            <value>
                /login.jsp = anon
                /shiro/login = anon
                
                /shiro/logout = logout
                
                /user.jsp=roles[sdl]
                /admin.jsp=roles[admin]
                
                /** = authc
            </value>
        </property>-->
       
    </bean>
    <!-- 配置一个bean,实际上是一个map,通过实例工程的方法 -->
    <bean id="filterChainDefinitionMap" 
    	factory-bean="filterChainDefinitionMapBuilder" factory-method="builderFilterChainDefinitionMap">
    	
    </bean>
    <bean id="filterChainDefinitionMapBuilder" class="com.liang.factory.FilterChainDefinitionMapBuilder">
    	
    </bean>
    
</beans>

ehcache.xml

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<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"/>


    <!--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>


springmvc.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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
	<!-- 扫描注解,只扫描controller -->
	<context:component-scan base-package="com.liang.controller"></context:component-scan>
	<!-- 注解驱动 ,注册HandlerMapper,HandlerAdapter-->                         	
    <mvc:annotation-driven></mvc:annotation-driven>	
    <!-- 静态资源 -->
    <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
    <mvc:resources location="/image/" mapping="/image/**"></mvc:resources>
    
    <!-- 自定义视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	<property name="prefix" value="/"></property>
    	<property name="suffix" value=".jsp"></property>
    </bean>
    <!-- MultiPartResolver解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
</beans>

以及日志文件log4j.properties

4、在com.liang.realm包下新建类ShiroRealm.java,继承AuthorizingRealm

ShiroRealm.java

package com.liang.realm;

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.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
/**
 * 用于认证
 * @author Administrator
 *
 */
public class ShiroRealm  extends AuthorizingRealm{
	//用于认证的方法
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("-------------------ShiroRealm-------------------");
		//1.把AuthenticationToken转为UsernamePasswordToken
		UsernamePasswordToken upToken=(UsernamePasswordToken) token;
		//2.从UsernamePasswordToken中获取username
		String username = upToken.getUsername();
		//3.调用数据库方法
		System.out.println("从数据库中获取信息username:"+username);
		//4.若用户不存在抛出异常
		if("unknown".equals(username)) {
			throw new UnknownAccountException("用户不存在");
		}
		//5.根据用户情况,是否需要抛出其他异常
		if("monster".equals(username)) {
			throw new LockedAccountException("用户被锁定");
		}
		//6.根据用户情况,来构建AuthenticationInfo对象并返回,通常使用SimpleAuthenticationInfo,
		//principal, credentials, realmNames信息从数据库中获取
		Object principal=username;//认证的实体信息,可以是一个字段,也可是一个记录
		Object credentials=null;//"4a95737b032e98a50c056c41f2fa9ec6";//密码,MD5加密后的值
		String realmName=this.getName();//当前realm的name
		ByteSource credentialsSalt=ByteSource.Util.bytes(username);//盐值,一般使用随机字符串或 user id,即使两个人的明文密码一样,加密后的密码也是不一样的
		
		SimpleAuthenticationInfo info=null;//new SimpleAuthenticationInfo(principal, credentials, realmName);
		
		if("admin".equals(username)) {
			credentials="cf2f84b6b83710fd7442ede509c95012";
		}
		if("sdl".equals(username)) {
			credentials="00165889ee76ac2f6dc33c7187195948";
		}
		info=new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
		return info;
	}
	//用于授权的方法
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		System.out.println("----------------doGetAuthorizationInfo---------");
		//1.同过PrincipalCollection获取用户信息
		Object principal = principals.getPrimaryPrincipal();
		//2.利用登录信息获取当前用户角色或权限,可能需要查询数据库
		Set<String> roles=new HashSet<String>();
		roles.add("sdl");
		if("admin".equals(principal)) {
			roles.add("admin");
		}
		//3.构建AuthorizationInfo对象并返回,通常使用SimpleAuthorizationInfo
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(roles);
		return info;
	}

	
//	  public static void main(String[] args) {
//		  SimpleHash hash = new SimpleHash("MD5", "123456", ByteSource.Util.bytes("sdl"), 10); 
//		  System.out.println(hash); 
//	  }
	 
}

5、在com.liang.factory包下新建类FilterChainDefinitionMapBuilder.java

package com.liang.factory;

import java.util.LinkedHashMap;
/**
			配置哪些页面需要受保护,以及访问这些页面需要的权限
        	anon可以被匿名访问
        	authc必须认证之后才能被访问,即登录后
        	logout 登出过滤器
        	roles角色过滤器

 */
public class FilterChainDefinitionMapBuilder {
	public LinkedHashMap<String, String> builderFilterChainDefinitionMap(){
		
		LinkedHashMap<String, String> map =new LinkedHashMap<String, String>();
		map.put("/login.jsp", "anon");
		//map.put("/shiro/login", "anon");
		
		//map.put(" /shiro/logout", "logout");
		
		//map.put("/user.jsp", "authc,roles[sdl]");
		//map.put("/admin.jsp", "authc,roles[admin]");
		//map.put("/list.jsp", "user");
		
		
		map.put("/**", "authc");
		return map;
		
	}
}

6、测试

在项目下新建login.jsp,list.jsp
login.jsp可以正常访问,list.jsp不能访问会被重定向到login.jsp

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CSDN IT狂飙上传的代码均可运行,功能ok的情况下才上传的,直接替换数据即可使用,小白也能轻松上手 【资源说明】 基于MATLAB实现的GO-CFAR检测是信号处理中非常常用的检测方法该程序比较了理论值和实际值的仿真结果实际中雷达信号往往是起伏的,该程序从SweringI型为例+使用说明文档 1、代码压缩包内容 主函数:main.m; 调用函数:其他m文件;无需运行 运行结果效果图; 2、代码运行版本 Matlab 2020b;若运行有误,根据提示GPT修改;若不会,私信博主(问题描述要详细); 3、运行操作步骤 步骤一:将所有文件放到Matlab的当前文件夹中; 步骤二:双击打开main.m文件; 步骤三:点击运行,等程序运行完得到结果; 4、仿真咨询 如需其他服务,可后台私信博主; 4.1 期刊或参考文献复现 4.2 Matlab程序定制 4.3 科研合作 功率谱估计: 故障诊断分析: 雷达通信:雷达LFM、MIMO、成像、定位、干扰、检测、信号分析、脉冲压缩 滤波估计:SOC估计 目标定位:WSN定位、滤波跟踪、目标定位 生物电信号:肌电信号EMG、脑电信号EEG、心电信号ECG 通信系统:DOA估计、编码译码、变分模态分解、管道泄漏、滤波器、数字信号处理+传输+分析+去噪、数字信号调制、误码率、信号估计、DTMF、信号检测识别融合、LEACH协议、信号检测、水声通信 5、欢迎下载,沟通交流,互相学习,共同进步!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值