返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot中shiro过滤器的重写与配置详解
  • 799
分享到

SpringBoot中shiro过滤器的重写与配置详解

2024-04-02 19:04:59 799人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

目录问题解决方案实现代码1.重写shiro 登录 过滤器2.重写role权限 过滤器3.配置过滤器问题 遇到问题:在前后端分离跨域访问的项目中shiro进行权限拦截失效 (即使有正确

问题

遇到问题:在前后端分离跨域访问的项目中shiro进行权限拦截失效 (即使有正确权限的访问也会被拦截) 时造成302重定向错误等问题
报错:Response for preflight is invalid (redirect)

1.302原因:使用ajax访问后端项目时无法识别重定向操作

2.shiro拦截失效原因:跨域访问时有一种带预检访问的跨域,即访问时先发出一条methods为OPTioNS的的访问,这种访问不带cookie等信息。造成shiro误判断为无权限访问。

3.一般使用的访问methods都是:get,post,put,delete

解决方案

1.让shiro不对预检访问拦截

2. 改变shiro中无权限,未登录拦截的重定向,这就需要重写几个过滤器

3. 将重写的过滤器进行配置

实现代码

1.重写shiro 登录 过滤器

过滤器运行机制:

(1)shiro是否拦截访问 以 isAccessAllowed返回值为准

(2)如果isAccessAllowed 方法返回false会进入onAccessDenied方法重定向至 登录 or 无权限 页面

package com.yaoxx.base.shiro;

import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.Http.httpservletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.WEB.filter.authc.FORMAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;



public class MyAuthenticationFilter extends FormAuthenticationFilter {
   
   @Override
   protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
   	boolean allowed = super.isAccessAllowed(request, response, mappedValue);
   	if (!allowed) {
   		// 判断请求是否是options请求
   		String method = WebUtils.toHttp(request).getMethod();
   		if (StringUtils.equalsIgnoreCase("OPTIONS", method)) {
   			return true;
   		}
   	}
   	return allowed;
   }

   @Override
   protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
   	if (isLoginRequest(request, response)) { // 判断是否登录
   		if (isLoginSubmission(request, response)) { // 判断是否为post访问
   			return executeLogin(request, response);
   		} else {
   			// sessionID已经注册,但是并没有使用post方式提交
   			return true;
   		}
   	} else {
   		HttpServletRequest req = (HttpServletRequest) request;
   		HttpServletResponse resp = (HttpServletResponse) response;
   		
//			if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
//				resp.setStatus(HttpStatus.OK.value());
//				return true;
//			}
   		
   		String ajaxHeader = req.getHeader(CustomSessionManager.AUTHORIZATION);
   		if (StringUtils.isNotBlank(ajaxHeader)) {
   			// 前端Ajax请求,则不会重定向
   			resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
   			resp.setHeader("Access-Control-Allow-Credentials", "true");
   			resp.setContentType("application/JSON; charset=utf-8");
   			resp.setCharacterEncoding("UTF-8");
   			resp.setStatus(HttpStatus.UNAUTHORIZED.value());//设置未登录状态码
   			PrintWriter out = resp.getWriter();
//				Map<String, String> result = new HashMap<>();
//				result.put("MESSAGE", "未登录用户");
   			String result = "{"MESSAGE":"未登录用户"}";
   			out.println(result);
   			out.flush();
   			out.close();
   		} else {
   			// == 如果是普通访问重定向至shiro配置的登录页面 == //
   			saveRequestAndRedirectToLogin(request, response);
   		}
   	}
   	return false;
   }
}

2.重写role权限 过滤器

package com.yaoxx.base.shiro;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;



public class MyAuthorizationFilter extends RolesAuthorizationFilter {

   @Override
   public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
   		throws IOException {
   	boolean allowed =super.isAccessAllowed(request, response, mappedValue);
   	if (!allowed) {
   		String method = WebUtils.toHttp(request).getMethod();
   		if (StringUtils.equalsIgnoreCase("OPTIONS", method)) {
   			return true;
   		}
   	}
   	return allowed;
   }

   @Override
   protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
   	HttpServletRequest req = (HttpServletRequest) request;
   	HttpServletResponse resp = (HttpServletResponse) response;
   	if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
   		resp.setStatus(HttpStatus.OK.value());
   		return true;
   	}
   	// 前端Ajax请求时requestHeader里面带一些参数,用于判断是否是前端的请求
   	String ajaxHeader = req.getHeader(CustomSessionManager.AUTHORIZATION);
   	if (StringUtils.isNotBlank(ajaxHeader)) {
   		// 前端Ajax请求,则不会重定向
   		resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
   		resp.setHeader("Access-Control-Allow-Credentials", "true");
   		resp.setContentType("application/json; charset=utf-8");
   		resp.setCharacterEncoding("UTF-8");
   		PrintWriter out = resp.getWriter();
   		String result = "{"MESSAGE":"角色,权限不足"}";
   		out.println(result);
   		out.flush();
   		out.close();
   		return false;
   	}
   	return super.onAccessDenied(request, response);
   }
}

3.配置过滤器

@Configuration
public class ShiroConfiguration {
	
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	
	
	
	
	@Bean("shiroFilter")
	public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager")SecurityManager manager) {
		ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
		bean.setSecurityManager(manager);
		
		Map<String, Filter> filters = bean.getFilters(); 
		filters.put("authc", new MyAuthenticationFilter());
		filters.put("roles", new MyAuthorizationFilter());

		
		Map<String, String> filterChainDefinitionMap =new LinkedHashMap<>();
		filterChainDefinitionMap.put("/login", "anon");
//		filterChainDefinitionMap.put("/*", "authc");
//		filterChainDefinitionMap.put("/admin", "authc,roles[ADMIN]");
		bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
		
		return bean;
	}

以上就是SpringBoot中shiro过滤器的重写与配置详解的详细内容,更多关于SpringBoot shiro过滤器重写配置的资料请关注编程网其它相关文章!

--结束END--

本文标题: SpringBoot中shiro过滤器的重写与配置详解

本文链接: https://lsjlt.com/news/147469.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作