shiro整合spring

shiro整合spring

参考官网文档 http://shiro.apache.org/spring.html

1、pom.xml配置

	 <!-- shiro的core web spring整合的 引入  -->
   	<dependency>
		<groupId>org.apache.shiro</groupId>
		<artifactId>shiro-core</artifactId>
		<version>1.3.2</version>
    </dependency>
    <dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-log4j12</artifactId>
		<version>1.7.21</version>
	</dependency>
    <dependency>
		<groupId>org.apache.shiro</groupId>
		<artifactId>shiro-web</artifactId>
		<version>1.3.2</version>
	</dependency>
	<dependency>
	    <groupId>org.apache.shiro</groupId>
	    <artifactId>shiro-spring</artifactId>
	    <version>1.3.2</version>
	</dependency>

2、web.xml配置

<!-- shiro过滤器定义 -->
	<filter>  
	    <filter-name>shiroFilter</filter-name>  
	    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
		<init-param>  
			<!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->  
			<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-shiro.xml配置

在spring.xml中载入一个spring-shiro.xml

    <!--载入spring-shiro.xml 配置  -->
   <import resource="classpath:spring-shiro.xml"/>

spring-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"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:cache="http://www.springframework.org/schema/cache"
 xmlns:util="http://www.springframework.org/schema/util"
 xsi:schemaLocation="
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-4.3.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
          http://www.springframework.org/schema/cache
          http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
          http://www.springframework.org/schema/util
          http://www.springframework.org/schema/util/spring-util-2.0.xsd ">
          
     
     <!-- 自定义Realm -->
	<bean id="myRealm" class="com.tingcream.shiroSpring.realm.MyRealm"/>  
	
	<!-- 自定义的登陆过滤器  /home=authc,userSession -->
	<bean id="userSessionFilter" class="com.tingcream.shiroSpring.common.UserSessionFilter"/>
	 
	<!-- 安全管理器 -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
  	  <property name="realm" ref="myRealm"/>  
	</bean>  
	
	<!-- Shiro过滤器 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
	    <!-- Shiro的核心安全接口,这个属性是必须的 -->  
	    <property name="securityManager" ref="securityManager"/>
	    <!-- 身份认证失败,则跳转到登录页面的配置 -->  
	    <property name="loginUrl" value="/login"/>
	    <!-- 权限认证失败,则跳转到指定页面 -->  
	    <property name="unauthorizedUrl" value="/unauthorized"/>  
		
		<!-- 自定义的访问控制filter -->
		<property name="filters">
	        <util:map>
	            <entry key="userSession" value-ref="userSessionFilter"/>
	            
	        </util:map>
	    </property>
	    
	    <property name="filterChainDefinitions">  
	        <value>  
                 /resources/**=anon
	             /login=anon
	             /home=authc,userSession
                 /logout=logout
                 /student/**=roles[student]
                 /teacher/**=perms[teacher:find]
				 /**=authc
	        </value>  
	    </property>
	</bean>  
	
	<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->  
	<bean id="lifecycleBeanPostProcessor"
          class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  
	
	<!-- 开启Shiro的权限注解 -->
	<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>  
    
</beans>

4、自定义realm

package com.tingcream.shiroSpring.realm;

import java.util.Set;

import org.apache.shiro.SecurityUtils;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.tingcream.shiroSpring.mapper.UserMapper;
import com.tingcream.shiroSpring.model.User;

public class MyRealm extends AuthorizingRealm{
	
	@Autowired
	private  UserMapper userMapper ;
	 

	/**
	 * 对当前subject进行权限认证(授权)
	 * @param principals
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username=(String)principals.getPrimaryPrincipal();
		
		SecurityUtils.getSubject().getSession();
		SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
		Set<String> roleNames=userMapper.findUserRoleNames(username);
		
		Set<String> permNames=userMapper.findUserPermNames(username);
		authorizationInfo.setRoles(roleNames);
		authorizationInfo.setStringPermissions(permNames);
		return authorizationInfo;
		  
	}

	/**
	 * 对当前subject进行身份认证
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		  
		String username=(String)token.getPrincipal();
		
		User user =userMapper.findUserByUsername(username);
		if(user==null) {
			//登陆失败
			return null;
		}
		AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),this.getClass().getSimpleName());
		return authcInfo;
		
	}	
}

5、自定义shiro登陆成功后的filter过滤器

package com.tingcream.shiroSpring.common;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.beans.factory.annotation.Autowired;
import com.tingcream.shiroSpring.mapper.UserMapper;
import com.tingcream.shiroSpring.model.User;

/**
 * shiro用户登陆成功后,经过这个过滤器处理,保存用户实体对象到session中
 * @author jelly
 *
 */
public class UserSessionFilter extends AccessControlFilter {
	
	@Autowired
	private UserMapper userMapper;

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		 
		  Subject subject =    this.getSubject(request, response);
			if(subject==null) {
				return false;
			}
			
			String username=  (String) subject.getPrincipal();
			
			//  HttpSession session = WebUtils.toHttp(request).getSession();
			org.apache.shiro.session.Session session = subject.getSession();
			User sessionUser =(User)session.getAttribute("sessionUser");
			if(sessionUser==null) {
				//根据用户名到数据库中查询
				 sessionUser=userMapper.findUserByUsername(username);
			}
		    session.setAttribute("sessionUser", sessionUser);
		
		 return true;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		return true;
	}

}

完整shiro+spring整合的项目参考笔者gitee.com仓库: https://gitee.com/mmxl/shiroSpring

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Shiro框架与Spring Boot的整合相对简单,可以通过一些配置和依赖来实现。以下是一个基本的整合示例: 1. 在Spring Boot的pom.xml文件中添加Shiro和Web依赖: ```xml <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-web-starter</artifactId> <version>1.8.0</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.8.0</version> </dependency> ``` 2. 创建一个Shiro配置类,用于配置Shiro相关的Bean和过滤器: ```java @Configuration public class ShiroConfig { @Bean public Realm realm() { return new MyRealm(); // 自定义的Realm实现 } @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) { ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean(); factoryBean.setSecurityManager(securityManager); // 配置过滤规则等 // factoryBean.setFilterChainDefinitionMap(...); return factoryBean; } @Bean public DefaultWebSecurityManager securityManager(Realm realm) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(realm); return securityManager; } } ``` 3. 创建一个自定义的Realm实现,用于处理身份认证和权限授权逻辑: ```java public class MyRealm extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // 处理授权逻辑 return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 处理认证逻辑 return null; } } ``` 4. 在Spring Boot的application.properties或application.yml文件中配置Shiro相关属性: ```yaml shiro: loginUrl: /login successUrl: /home unauthorizedUrl: /unauthorized ``` 这样,你就完成了Shiro框架与Spring Boot的整合。你可以根据自己的需求继续配置Shiro的过滤规则、权限配置等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值