search
HomeJavajavaTutorialMethods of rewriting and configuring shiro filters in SpringBoot

Problem

Encountered a problem: In a project that separates cross-domain access from the front and back ends, shiro's permission interception fails (even access with correct permissions will be intercepted), causing problems such as 302 redirect errors
Error report: Response for preflight is invalid (redirect)

1.302 Reason: The redirect operation cannot be recognized when using ajax to access the back-end project

2.Shiro interception failure reason: During cross-domain access There is a kind of cross-domain access with preflight access, that is, when accessing, an access with methods of OPTIONS is first issued. This access does not include cookies and other information. This causes Shiro to mistakenly judge that access is without permission.

3. Generally used access methods are: get, post, put, delete

Solution

1. Let shiro not intercept preflight access

2. Change the redirection blocked by shiro without permission and without login, which requires rewriting several filters

3. Configure the rewritten filters

Implementation code

1. Rewrite shiro login filter

Filter operating mechanism:

(1)Whether shiro intercepts access shall be based on the return value of isAccessAllowed

(2) If the isAccessAllowed method returns false, it will enter the onAccessDenied method and redirect to the login or non-permission page

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;

/**
*  
* @version: 1.0
* @since: JDK 1.8.0_91
* @Description:
* 		未登录过滤器,重写方法为【跨域的预检访问】放行

*/

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;
   		/*
   		 * 跨域访问有时会先发起一条不带token,不带cookie的访问。
   		 * 这就需要我们抓取这条访问,然后给他通过,否则只要是跨域的访问都会因为未登录或缺少权限而被拦截
   		 * (如果重写了isAccessAllowed,就无需下面的判断)
   		 */
//			if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
//				resp.setStatus(HttpStatus.OK.value());
//				return true;
//			}
   		/*
   		 * 跨域的第二次请求就是普通情况的request了,在这对他进行拦截
   		 */
   		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. Rewrite the role permission filter

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;

/**
* 
* @author: yao_x_x
* @since: JDK 1.8.0_91
* @Description: role的过滤器
*/

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. Configure the filter

@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);
		/* 自定义filter注册 */
		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;
	}

The above is the detailed content of Methods of rewriting and configuring shiro filters in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software