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
Are there any emerging technologies that threaten or enhance Java's platform independence?Are there any emerging technologies that threaten or enhance Java's platform independence?Apr 24, 2025 am 12:11 AM

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages ​​for performance.

What are the different implementations of the JVM, and do they all provide the same level of platform independence?What are the different implementations of the JVM, and do they all provide the same level of platform independence?Apr 24, 2025 am 12:10 AM

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages ​​and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

How does platform independence reduce development costs and time?How does platform independence reduce development costs and time?Apr 24, 2025 am 12:08 AM

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.

How does Java's platform independence facilitate code reuse?How does Java's platform independence facilitate code reuse?Apr 24, 2025 am 12:05 AM

Java'splatformindependencefacilitatescodereusebyallowingbytecodetorunonanyplatformwithaJVM.1)Developerscanwritecodeonceforconsistentbehavioracrossplatforms.2)Maintenanceisreducedascodedoesn'tneedrewriting.3)Librariesandframeworkscanbesharedacrossproj

How do you troubleshoot platform-specific issues in a Java application?How do you troubleshoot platform-specific issues in a Java application?Apr 24, 2025 am 12:04 AM

To solve platform-specific problems in Java applications, you can take the following steps: 1. Use Java's System class to view system properties to understand the running environment. 2. Use the File class or java.nio.file package to process file paths. 3. Load the local library according to operating system conditions. 4. Use VisualVM or JProfiler to optimize cross-platform performance. 5. Ensure that the test environment is consistent with the production environment through Docker containerization. 6. Use GitHubActions to perform automated testing on multiple platforms. These methods help to effectively solve platform-specific problems in Java applications.

How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.