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 solve the problem that SpringBoot+Spring Security can't realize cross-domain

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

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge that SpringBoot+Spring Security can not achieve cross-domain solution, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this SpringBoot+Spring Security article on how to solve cross-domain problem. Let's take a look at it.

SpringBoot+Spring Security cannot achieve cross-domain without using Security: import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.autoconfigure.AutoConfigureBefore;import org.springframework.context.annotation.Configuration;import org.springframework.format.FormatterRegistry;import org.springframework.web.servlet.config.annotation.*;@Configuration@AutoConfigureBefore (SecurityConfig.class) public class MyMvcConfigurer implements WebMvcConfigurer {public void addCorsMappings (CorsRegistry registry) {LOGGER.info ("Cross-domain set") Registry.addMapping ("/ *") .allowedOrigins ("*") .allowedMethods ("*") .allowedHeaders ("*") .allowCredentials (true) .maxAge (3600);}}

When integrating Security, it is found that there is still a cross-domain problem when only using the above method to separate the front and rear ends.

The solution is as follows: @ Configuration@AutoConfigureBefore (Swagger2Configuration.class) @ EnableWebSecurity@EnableGlobalMethodSecurity (prePostEnabled = true) @ Order (- 1) public class SecurityConfig extends WebSecurityConfigurerAdapter {@ Override protected void configure (HttpSecurity http) throws Exception {http.formLogin () .loginProcessingUrl ("/ user/login") .loginPage ("/ singIn.html") .roomHandler (moyuAuthenticationSuccessHandler) .failureHandler (moyuAuthenticationFailureHandler) .and () .apply (moyuSocialSecurityConfig) .and () .rememberMe () .tokenRepository (persistentTokenRepository ()) .tokenValiditySeconds (360024 hours 7) .userDetailsService (userDetailsService) .and () .authorizeRequests ( ) .antMatrices ("/ user/login") "/ login", "/ singIn.html", "* *", "/ * *"). PermitAll () .anyRequest () .authenticated () and () .cors () .and () .csrf () .disable () }} focus on adding code: .and () .cors () / / newly added .and () .csrf () .disable (); cross-domain processing of referencing Spring Security projects

Recently, the project has adopted a framework of front and back end separation, and the front-end and back-end interfaces have not been deployed to a site, so there is a cross-domain problem. What is cross-domain? I will not elaborate on it here, but directly talk about the solution.

There are many ways for Spring to solve cross-domain problems, and individuals adopt the Crosfilter approach.

The specific code is as follows:

Bean public CorsFilter corsFilter () {final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource (); final CorsConfiguration corsConfiguration = new CorsConfiguration (); corsConfiguration.setAllowCredentials (true); corsConfiguration.addAllowedOrigin ("*"); corsConfiguration.addAllowedHeader ("*"); corsConfiguration.addAllowedMethod ("*"); urlBasedCorsConfigurationSource.registerCorsConfiguration ("/ * *", corsConfiguration); return new CorsFilter (urlBasedCorsConfigurationSource);}

After the configuration is completed, the test call returns an error of 401, which still fails. According to the information found on the Internet, cross-domain requests will be made twice. The specific process is shown in the following figure:

For each cross-domain request, before the real request reaches the backend, the browser will first launch a preflight request. The request method is OPTIONS to ask the server whether to accept the cross-domain request. The specific parameters are shown below:

However, the request cannot carry cookie and self-defined header.

Because Spring security is introduced in the project, and the token delivery method I use is to use the authorization field in header, so relying on Spring Security to intercept until preflight request finds that it does not carry token, it will report an error 401without authorization.

To solve this problem, you can use the following configuration

Ask Spring security not to verify preflight request.

@ Override public void configure (HttpSecurity http) throws Exception {ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry registry = http.authorizeRequests (); registry.requestMatchers (CorsUtils::isPreFlightRequest) .permitAll (); / / Let Spring security release all preflight request}

Try again and it is done, but the direct configuration of the backend to support cross-domain will result in two requests. In another way, it's okay to forward the request using Nginx.

This is the end of the article on "how to solve the problem that SpringBoot+Spring Security cannot achieve cross-domain". Thank you for reading! I believe that everyone has a certain understanding of "SpringBoot+Spring Security can not achieve cross-domain how to solve" knowledge, if you want to learn more knowledge, welcome to follow the industry information channel.

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

Internet Technology

Wechat

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

12
Report