前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Shiro 整合 Spring 第一次

Shiro 整合 Spring 第一次

作者头像
用户5927264
发布2019-07-31 18:12:13
2900
发布2019-07-31 18:12:13
举报
文章被收录于专栏:OSChinaOSChina
输入图片说明
输入图片说明
代码语言:javascript
复制
<!-- shiro的配置 -->
		<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
		<dependency>
		    <groupId>org.apache.shiro</groupId>
		    <artifactId>shiro-core</artifactId>
		    <version>1.2.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-web -->
		<dependency>
		    <groupId>org.apache.shiro</groupId>
		    <artifactId>shiro-web</artifactId>
		    <version>1.2.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
		<dependency>
		    <groupId>org.apache.shiro</groupId>
		    <artifactId>shiro-spring</artifactId>
		    <version>1.2.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-ehcache -->
		<dependency>
		    <groupId>org.apache.shiro</groupId>
		    <artifactId>shiro-ehcache</artifactId>
		    <version>1.2.3</version>
		</dependency>
输入图片说明
输入图片说明
代码语言:javascript
复制
<!-- shiro的filter -->
  <!-- shiro的过滤器,DeleagtionFilterProxy通过代理模式将spring容器中的bean的filter关联起来 -->
  <filter>
  		<filter-name>shiroFilter</filter-name>
  		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  		<!-- 设置true 表示由sevlet容器控制filter的生命周期 -->
  		<init-param>
  			<param-name>targetFilterLifecycle</param-name>
  			<param-value>true</param-value>
  		</init-param>
  		
  		<!-- 设置spring容器的bean  id,如果不设置则找与filter-name一致的bean -->
  		<init-param>
  			<param-name>targetBeanName</param-name>
  			<param-value>shiroFilter</param-value>
  		</init-param>
  </filter>
 <filter-mapping>
  	<filter-name>shiroFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
输入图片说明
输入图片说明
代码语言:javascript
复制
<?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:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	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/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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- 1  配置filter对应的bean -->
 		<!-- shiro的web过滤器 -->
		<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
			<!-- 1.1 配置安全管理器 -->
			<property name="securityManager" ref="securityManager"/>
			<!-- 1.2 loginUrl认证提交地址,如果没有认证将会请求此地址进行认证,请求此地址将由formAuthenticationFilter进行表单认证-->
			<property name="loginUrl" value="/Login.action"/>
			<!-- 1.3  unauthorizedUrl指定没有权限时跳转页面-->
			<property name="unauthorizedUrl" value="refuse.jsp" />
			<!-- 1.4  过滤器链的定义 -->
			<property name="filterChainDefinitions">
				<value>
					<!-- /**=anon anon所有的url都可以匿名访问 -->
					/**=anon
				</value>
			</property>
		</bean>
<!-- 2  配置安全管理器  securityManager-->
		<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
			<property name="realm" ref="customRealm"></property>
		</bean>
		

<!-- 3  配置realm -->
		<bean id="customRealm" class="com.shi.shiro.CustomRealm"></bean>
</beans>

1 认证

输入图片说明
输入图片说明
输入图片说明
输入图片说明
代码语言:javascript
复制
package com.shi.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.shi.exception.CustomException;

@Controller
public class LoginController {

	//登录提交地址,和applicationContext-shiro.xml文件 中配置的loginUrl保持一致
	@RequestMapping("Login")
	public String Login(HttpServletRequest request) throws Exception{
		
		//如果失败从request中获取认证异常信息,shiroLoginFilure就是shiro异常类的权限类名
		String exceptionClassName=(String) request.getAttribute("shiroLoginFailure");
		
		System.out.println("登录异常=========="+exceptionClassName);
		
		//根据shiro返回的异常类路径判断,抛出指定异常信息
		if(exceptionClassName!=null){
			if(UnknownAccountException.class.getName().equals(exceptionClassName)){
				throw new CustomException("账户不存在");
			}else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)){
				System.out.println("密码错误");
				throw new CustomException("用户名/密码错误");
			}else{
				throw new Exception();//最终在异常处理器生成未知异常
			}
		}
		/**
		 * 此方法不处理登录成功(认证成功),shiro认证成功会自动跳转到上一个请求路径
		 * 登录失败还到login页面
		 */
		return "login";
	}
}
输入图片说明
输入图片说明
代码语言:javascript
复制
<?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:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	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/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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- 1  配置filter对应的bean -->
 		<!-- shiro的web过滤器 -->
		<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
			<!-- 1.1 配置安全管理器 -->
			<property name="securityManager" ref="securityManager"/>
			<!-- 1.2 loginUrl认证提交地址,如果没有认证将会请求此地址进行认证,请求此地址将由formAuthenticationFilter进行表单认证-->
			<property name="loginUrl" value="/login.action" />
			<!-- 1.3  unauthorizedUrl指定没有权限时跳转页面-->
			<property name="unauthorizedUrl" value="refuse.jsp" />
			
			<!-- 1.5  配置成功页面 -->
			<property name="successUrl" value="/first.action"/>
			<!-- 1.4  过滤器链的定义 -->
			<property name="filterChainDefinitions">
				<value>
					<!-- 对静态资源进行匿名访问 -->
					/images/**=anon
					<!-- 请求logout.action地址,shiro去清空session -->
					/logout.action=logout
					<!-- /**=authc 表示所有url都必须认证通过之后开可以访问 -->
					/**=authc
					
					<!-- /**=anon anon所有的url都可以匿名访问 -->
					<!-- /**=anon -->
				</value>
			</property>
		</bean>
<!-- 2  配置安全管理器  securityManager-->
		<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
			<property name="realm" ref="customRealm"></property>
		</bean>
		

<!-- 3  配置realm -->
		<bean id="customRealm" class="com.shi.shiro.CustomRealm"></bean>
</beans>
输入图片说明
输入图片说明
输入图片说明
输入图片说明
输入图片说明
输入图片说明
输入图片说明
输入图片说明

2 授权

2.1 授权的配置文件

代码语言:javascript
复制
<?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:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	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/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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- 1  配置filter对应的bean -->
 		<!-- shiro的web过滤器 -->
		<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
			<!-- 1.1 配置安全管理器 -->
			<property name="securityManager" ref="securityManager"/>
			<!-- 1.2 loginUrl认证提交地址,如果没有认证将会请求此地址进行认证,请求此地址将由formAuthenticationFilter进行表单认证-->
			<property name="loginUrl" value="/login.action" />
			<!-- 1.3  unauthorizedUrl指定没有权限时跳转页面-->
			<property name="unauthorizedUrl" value="refuse.jsp" />
			
			<!-- 1.5  配置成功页面 -->
			<property name="successUrl" value="/first.action"/>
			<!-- 1.4  过滤器链的定义 -->
			<property name="filterChainDefinitions">
				<value>
					<!-- 对静态资源进行匿名访问 -->
					/images/**=anon
					<!-- 请求logout.action地址,shiro去清空session -->
					/logout.action=logout
					<!-- /**=authc 表示所有url都必须认证通过之后开可以访问 -->
					
					<!-- 授权的控制 -->
					/items/query.action=perms[items:query]
					/user/query.action=perms[user:query]
					
					<!-- 对所有剩下的认证 -->
					/**=authc
					<!-- /**=anon anon所有的url都可以匿名访问 -->
					<!-- /**=anon -->
				</value>
			</property>
		</bean>
<!-- 2  配置安全管理器  securityManager-->
		<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
			<property name="realm" ref="customRealm"></property>
		</bean>
		

<!-- 3  配置realm -->
		<bean id="customRealm" class="com.shi.shiro.CustomRealm"></bean>
</beans>

2.2 自定义的realm

代码语言:javascript
复制
package com.shi.shiro;

import java.util.ArrayList;
import java.util.List;

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 com.shi.pojo.ActiveUser;

public class CustomRealm extends AuthorizingRealm{

	//设置realm的名字
	@Override
	public void setName(String name) {
		super.setName("customRealm");
	}
	
	
	/**
	 * 用于认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		//1 从token中取出身份信息(token是用户输入的)
		String userCode=(String) token.getPrincipal();
		System.out.println("token.getPrincipal="+userCode); //打印出:zhangsan
		System.out.println("token.getCredentials="+token.getCredentials());//打印出:[C@3c3aeae4
		
		//2 根据用户输入的userCode从数据库查询
		//...  模拟数据库中取出的密码是"111111"
		String password="123456";
		
		//3 如果 查询不到返回null
		/*if(!"zhangsan".equals(userCode)){
			return null;
		}*/
		
		//把用户信息封装到ActiveUser中
		ActiveUser activeUser=new ActiveUser();
		activeUser.setUserId(1);
		activeUser.setUserName("张三");
		activeUser.setUserPassword("123456");
		
		List<String> meniuList =new ArrayList<String>();
		meniuList.add("用户管理");
		meniuList.add("商品管理");
		
		activeUser.setMeniuList(meniuList);
		
		//如果查询到 返回认证信息AuthenticationInfo
		//这里的用户信息可以存储字符串,或者自定义的pojo
		SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(activeUser, password, this.getName());
		
		return simpleAuthenticationInfo;
	}
	
	/**
	 * 用于授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		/**
		 * 1  从principals中获得主身份信息
		 * 将getPrimaryPrincipal方法返回值转为真实身份类型,
		 * (在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo)
		 */
		ActiveUser activeUser=(ActiveUser) principals.getPrimaryPrincipal();
		System.out.println("principals.权限控制中获取用户信息="+activeUser);//打印出:zhangsan
		
		/**
		 * 2  根据身份信息获取权限信息(从数据库中查询)
		 * 模拟查询到的数据
		 */
		List<String> permissions=new ArrayList<String>();
		permissions.add("user:create");//用户的创建
		permissions.add("items:add:1");//商品添加
		permissions.add("items:query");//商品查询
		//3 查询到数据返回授权信息
		SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
		//4  将上面查询到数据填充到SimpleAuthorizationInfo对象中
		simpleAuthorizationInfo.addStringPermissions(permissions);
		
		return simpleAuthorizationInfo;
	}

}

2.3 控制器

代码语言:javascript
复制
/**
	 * /items/query.action 查询商品的action
	 */
	@RequestMapping("/items/query.action")
	public ModelAndView queryItems()throws Exception{
		ModelAndView mv =new ModelAndView();
		
		mv.setViewName("queryItems");
		return mv;
	}

3 几点注意点

输入图片说明
输入图片说明
输入图片说明
输入图片说明
输入图片说明
输入图片说明
输入图片说明
输入图片说明
代码语言:javascript
复制
anon: 例子/admins/**=anon 没有参数,表示可以匿名使用。
authc: 例如/admins/user/**=authc表示需要认证(登录)才能使用,FormAuthenticationFilter是表单认证,没有参数 
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] ,其中method为post,get,delete等。
port: 例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString
是你访问的url里的?后面的参数。
authcBasic: 例如/admins/user/**=authcBasic没有参数表示httpBasic认证

ssl:  例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https
user:  例如/admins/user/**=user没有参数表示必须存在用户, 身份认证通过或通过记住我认证通过的可以访问,当登入操作时不做检查
注:
anon,authcBasic,auchc,user是认证过滤器,
perms,roles,ssl,rest,port是授权过滤器

4 基于 md5 认证 的配置方式

4.1 在applicationContext-shiro.xml文件中配置 凭证匹配器

代码语言:javascript
复制
<!-- 3  配置realm -->
		<bean id="customRealm" class="com.shi.shiro.CustomRealm">
			<property name="credentialsMatcher" ref="credentialsMatcher"></property>
		</bean>

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

</beans>

4.2 自定义realm中 认证配置

代码语言:javascript
复制
/**
	 * 用于认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		//1 从token中取出身份信息(token是用户输入的)
		String userCode=(String) token.getPrincipal();
		System.out.println("token.getPrincipal="+userCode); //打印出:zhangsan
		System.out.println("token.getCredentials="+token.getCredentials());//打印出:[C@3c3aeae4
		
		
		
		//3 如果 查询不到返回null
		if(!"zhangsan".equals(userCode)){
			return null;
		}
		
		//2 根据用户输入的userCode从数据库查询
		//...  模拟数据库中取出的密码是"123456"
		String password="588043b2413a9a1e26a623f58606f148";
		String salt="sjsii";
		
		
		//把用户信息封装到ActiveUser中
		ActiveUser activeUser=new ActiveUser();
		activeUser.setUserId(1);
		activeUser.setUserName("张三");
		activeUser.setUserPassword("123456");
		
		List<String> meniuList =new ArrayList<String>();
		meniuList.add("用户管理");
		meniuList.add("商品管理");
		
		activeUser.setMeniuList(meniuList);
		
		//如果查询到 返回认证信息AuthenticationInfo
		//这里的用户信息可以存储字符串,或者自定义的pojo
		SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo
				(activeUser, password,ByteSource.Util.bytes(salt), this.getName());
		
		return simpleAuthenticationInfo;
	}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1 认证
  • 2 授权
  • 3 几点注意点
  • 4 基于 md5 认证 的配置方式
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档