Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use CorsFilter to solve the problem of front-end cross-domain request in Security framework

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to use CorsFilter to solve the front-end cross-domain request problem in the Security framework". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use CorsFilter to solve the front-end cross-domain request problem in the Security framework.

Project situation

The recent pmdb project is separated from the front and back end, and the problem of cross-domain requests arises because the front-end and back-end are jointly debugged during the test.

By default, the browser sends an Options request to the backend, and determines which request methods are supported by the backend according to the response of the backend, and the support will actually send the request.

CORS introduction

CORS (Cross-Origin Resource Sharing cross-source resource sharing) is cross-domain when any of the protocols, domain names and ports of a request url are different from the current page address.

Cross-domain operations are inevitable in daily project development, but in the actual cross-domain requests, we often encounter similar No 'Access-Control-Allow-Origin' header is present on the requested resource. Such an error report.

Such errors are generally caused by incorrect settings of CORS cross-domain authentication mechanism.

Solution

Note: this project uses SprintBoot+Security+JWT+Swagger

The first step

Create a new CorsFilter and set the relevant request headers in the filter

Package com.handlecar.basf_pmdb_service.filter; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException; public class CorsFilter extends OncePerRequestFilter {/ / public class CorsFilter implements Filter {/ / static final String ORIGIN = "Origin" Protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {/ / String origin = request.getHeader (ORIGIN); response.setHeader ("Access-Control-Allow-Origin", "*"); / / * or origin as u prefer response.setHeader ("Access-Control-Allow-Credentials", "true") Response.setHeader ("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE"); response.setHeader ("Access-Control-Max-Age", "3600"); / / response.setHeader ("Access-Control-Allow-Headers", "content-type, authorization") Response.setHeader ("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Authorization"); response.setHeader ("XDomainRequestAllowed", "1"); / / enable the front end to obtain response.setHeader ("Access-Control-Expose-Headers", "download-status,download-filename,download-message") If (request.getMethod (). Equals ("OPTIONS")) / / response.setStatus (HttpServletResponse.SC_OK); response.setStatus (HttpServletResponse.SC_NO_CONTENT); else filterChain.doFilter (request, response) } / / @ Override// public void doFilter (ServletRequest req, ServletResponse res,// FilterChain chain) throws IOException, ServletException {/ HttpServletResponse response = (HttpServletResponse) res;// the test environment is matched with [*]. After entering the production environment, you need to switch to the actual frontend request address / / response.setHeader ("Access-Control-Allow-Origin", "*"). / response.setHeader ("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); / response.setHeader ("Access-Control-Max-Age", "0"); / / response.setHeader ("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, auth") / response.setHeader ("Access-Control-Allow-Credentials", "true"); / response.setHeader ("XDomainRequestAllowed", "1"); / / chain.doFilter (req, res); / /} / @ Override// public void destroy () {/ /} / @ Override// public void init (FilterConfig arg0) throws ServletException {/ /}}

Note: the request header of the Access-Control-Expose-Headers here is to enable the front end to get the header customized by the back end in the response. If not set, the front end can only see a few header displayed by default. When I use response to export Excel, I put the file name and download status information in the header of response in the form of custom request headers.

Step two

Initialize the Bean of CorsFilter in the configuration file of Security

@ Bean public CorsFilter corsFilter () throws Exception {return new CorsFilter ();} step 3

Add Filter configuration and mapping configuration to the configuration file of Security

.antMatrices (HttpMethod.OPTIONS, "/ * *") .permitAll () / / all requests except the above require authentication. .and () is equivalent to marking the end of a tag, which was previously equivalent to the content under the same tag item .anyRequest (). Authenticated (). And () .addFilterBefore (corsFilter (), UsernamePasswordAuthenticationFilter.class)

Attached: the profile

Package com.handlecar.basf_pmdb_service.conf;import com.handlecar.basf_pmdb_service.filter.CorsFilter;import com.handlecar.basf_pmdb_service.filter.JwtAuthenticationTokenFilter;import com.handlecar.basf_pmdb_service.security.JwtTokenUtil;import com.handlecar.basf_pmdb_service.security.CustomAuthenticationProvider;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpMethod Import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;//import com.allcom.security.JwtTokenUtil @ Configuration//@EnableWebSecurity is used to enable Spring Security's web security support and provide the Spring MVC integration@EnableWebSecurity@EnableGlobalMethodSecurity (prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter {private final CustomAuthenticationProvider customAuthenticationProvider; @ Autowired public WebSecurityConfig (CustomAuthenticationProvider customAuthenticationProvider) {this.customAuthenticationProvider = customAuthenticationProvider;} @ Override protected void configure (AuthenticationManagerBuilder auth) {auth.authenticationProvider (customAuthenticationProvider);} @ Bean public JwtTokenUtil jwtTokenUtil () {return new JwtTokenUtil () } @ Bean public CorsFilter corsFilter () throws Exception {return new CorsFilter ();} @ Bean public JwtAuthenticationTokenFilter authenticationTokenFilterBean () {return new JwtAuthenticationTokenFilter () } @ Override protected void configure (HttpSecurity httpSecurity) throws Exception {httpSecurity / / because we are using JWT, we do not need csrf here and do not have to worry about csrf attacks .csrf () .disable () / / based on token So there is no need for session .sessionManagement (). SessionCreationPolicy (SessionCreationPolicy.STATELESS). And () .authorizeRequests () / / .antMatchs (HttpMethod.OPTIONS, "/ * *"). PermitAll () / / to allow unauthorized access to static resources on the website.antMatch.antMatch.Match.Match.antMatch.Match.tMatch.tMatch.com (HttpMethod.GET) "/", "/ * .html", "/ favicon.ico", "/ * * / * .html", "/ * * / * .css", "/ * * / * .js" "/ webjars/springfox-swagger-ui/images/**", "/ swagger-resources/configuration/*", "/ swagger-resources" / / swagger request "/ v2/api-docs") .permitAll () / / allow anonymous access to .antMatrices ("/ pmdbservice/auth/**", "/ pmdbservice/keywords/export3") .antMatrices (HttpMethod.OPTIONS) for rest api that acquires token "/ * *") .permitAll () / / all requests except the above require authentication. .and () is equivalent to marking the end of a tag, which is equivalent to the content under the same tag item .anyRequest (). Authenticated (). And () .addFilterBefore (corsFilter (), UsernamePasswordAuthenticationFilter.class) .addFilterBefore (authenticationTokenFilterBean (), UsernamePasswordAuthenticationFilter.class); / / disable cache httpSecurity.headers () .FilterBefore (). CacheControl () }} at this point, I believe you have a deeper understanding of "how to use CorsFilter to solve the front-end cross-domain request problem in the Security framework". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report