3、SpringBoot 解决跨域问题

跨域资源共享(CORS)是前后端分离项目中常见的问题,它允许浏览器向跨源服务器发送XMLHttpRequest请求,这样就克服了ajax只能同源使用限制,而同源策略的限制主要是为了避免浏览器受到 XSS、CSFR 等的攻击。

跨域

当浏览器发出请求时,出现了下面任意一种情况,都可以视为跨域问题:

  • 协议不同:比如 http 和 https。
  • 域名不同:比如主域名和子域名。
  • 端口号不同。

比如,当前页面地址为http://www.xxw.com:8080/,而被请求页面地址为 https://www.xxw.com:8080/、https://blog.xxw.com:8080/、https://www.aaa.com:8080/、https://www.xxw.com:8888/ 等都属于跨域访问。

CORS(Cross-Origin Resource Sharing)是一种跨域资源共享技术方案,它支持多种 HTTP 请求方法,请求方法的不同,在处理上也有所不同。

1、简单请求

浏览器直接发送请求,并在请求头中增加一个 Origin 字段指定页面的域,如果服务端支持该跨域请求的话,则会在响应头返回 Access-Control-Allow-Origin 字段来告诉浏览器哪些域可以请求该资源,后边浏览器会根据该字段的值决定是否限制跨域请求。

当满足以下条件时,属于简单请求:

  • 只能有 GET、POST、HEAD 三种请求方式;
  • 请求头限制这几种字段:Accept、Accept-Language、Content-Language、Content-Type、Last-Event-ID;
  • Content-type只能取:application/x-www-form-urlencoded、multipart/form-data、text/plain。

2、复杂请求

当满足以下条件时,属于复杂请求:请求方法是 PUT、DELETE,或 Content-Type 类型是 application/json。

这些跨域请求会在正式发送前先发送一次 OPTIONS 类型的预检请求,预检请求头 Origin 用来指定发送请求的浏览器页面的域、Access-Control-Request-Method 用来指定跨域请求类型;服务端如果允许该跨域请求则会在响应头返回对应的字段 Access-Control-Allow-Origin、Access-Control-Allow-Method(允许跨域的请求类型)、Access-Control-Max-Age(预检请求的有效期,单位秒),预检请求完成后的就会发送真正的请求,与简单请求的步骤基本一致。

CORS 是目前解决前端跨域请求的主流方案,它支持多种 HTTP 请求方法,SpringBoot 解决跨域问题正是基于 CORS 的后端解决方案,下面进行介绍说明。

SpringBoot 解决跨域方案

1、使用 @CrossOrigin 注解

如果该注解用在控制器类上,则该控制器中的所有接口都支持跨域;如果用在指定接口上,则该接口支持跨域访问。

示例如下:

//origins:允许的域,* 表示所有,也可指定具体的域
@CrossOrigin(origins = "*")
@RestController
public class TestController {
    //@CrossOrigin(origins = "*")
    @GetMapping("/test")
    public String test() {
        return "test,test";
    }
}

该注解属于局部跨域配置,当有多个控制器类或多个指定接口需要跨域配置时,缺点也很明显,会做许多重复的配置操作,无法全局配置。

2、使用基于 WebMvcConfigurer 的配置类

使用基于 WebMvcConfigurer 的配置类,重写 addCorsMappings 方法,示例如下:

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .maxAge(3600L);
    }
}

部分属性说明:

  • addMapping:可被跨域请求的接口,/**表示所有;
  • allowedOrigins:允许的域,* 表示所有,也可指定具体的域;
  • allowCredentials:是否允许浏览器发送凭证信息,例如 Cookie;
  • allowedMethods:允许的请求方法(GET、POST ... );
  • allowedHeaders:允许的请求头字段,* 表示所有;
  • exposedHeaders:哪些响应头可以作为响应的一部分暴露出来;
  • maxAge: 预检请求的有效期,有效期内不用再发出预检请求。

这种方式和上面的 @CrossOrigin 注解方式配置属性和执行原理大致相似,在 DispatcherServlet 中触发跨域处理,配置了一个 CorsConfiguration 对象,然后用该对象创建 CorsInterceptor 拦截器,然后在拦截器中调用 DefaultCorsProcessor#processRequest 方法,完成对跨域请求的校验。

3、使用跨域过滤器 CorsFilter

由于过滤器的执行时机早于拦截器,使用 CorsFilter 过滤器方式处理跨域的时机早于前两种方式,示例如下:

@Configuration
public class CorsFilterConfig {

    @Bean
    public CorsFilter corsFilter() {
        //跨域配置
        CorsConfiguration config= new CorsConfiguration();
        config.setAllowCredentials(true);
        config.setAllowedMethods(Collections.singletonList("*"));
        config.setAllowedHeaders(Collections.singletonList("*"));
        config.setAllowedOrigins(Collections.singletonList("*"));
        config.setMaxAge(3600L);
        //添加地址映射
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        //加入CorsFilter对象中
        CorsFilter filter = new CorsFilter(source);
        return filter;
    }

}

执行机制,在跨域过滤器的 doFilterInternal 方法中调用  DefaultCorsProcessor#processRequest 方法,完成对跨域请求的校验;核心的配置和前两种方式相似,这里由 CorsConfiguration 来完成。

4、 Spring Security 引起的跨域失效问题

如果项目里引入了 Spring Security,则会导致第一种和第二种跨域方案失效,原因是 Spring Security 是基于过滤器的实现的(本质是 FilterChainProxy),而过滤器执行时机会早于拦截器,从而导致复杂请求的预检请求(OPTIONS)被 Spring Security 拦截了。因此,使用了 Spring Security 后不建议再使用这两种跨域解决方案。

同理,如果跨域过滤器 CorsFilter 设置的优先级低于 FilterChainProxy(默认100) 则使用 CorsFilter 方式也会失效。因此,我们可以设置 CorsFilter 的优先级高点(如Ordered.HIGHEST_PRECEDENCE),这样使用 Spring Security 就不会影响到 CorsFilter 了。

改造下第三种方式的代码即可,示例如下:

FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(filter);
registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registrationBean;

5、 Spring Security 优雅的跨域解决方案

当然,在 Spring Security 中已经提供了更加优雅的跨域解决方案,不必为前面的失效问题考虑。

配置类的示例如下:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("xxwei").password("123456").roles("admin").build());
        auth.userDetailsService(manager);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
//                .antMatchers(HttpMethod.OPTIONS).permitAll() // 放行 @CrossOrigin、addCorsMappings 的预检请求
                .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and()
                .formLogin()
//                .loginPage("/login")
                .loginProcessingUrl("/doLogin")
                .successHandler((httpServletRequest, httpServletResponse, authentication) -> {
                    User user = (User) authentication.getPrincipal();
                    writeMessage(httpServletResponse, new ObjectMapper().writeValueAsString(user));
                    System.out.println("login success");
                })
                .failureHandler((httpServletRequest, httpServletResponse, e) -> {
                    System.out.println("login failure");
                })
                .permitAll()
                .and()
                .logout()
                .logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> {
                    System.out.println("logout success");
                })
                .permitAll()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> {
                    response.setStatus(401);
                    writeMessage(response, "please login");
                    System.out.println("please login");
                })
                .and().cors().configurationSource(corsConfigurationSource()) // Spring Security 的跨域配置
                .and()
                .csrf().disable();
    }

    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config .setAllowedMethods(Collections.singletonList("*"));
        config .setAllowedHeaders(Collections.singletonList("*"));
        config .setAllowedOrigins(Collections.singletonList("*"));
        config .setAllowCredentials(true);
        config .setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }

    private void writeMessage(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(message);
        out.flush();
        out.close();
    }
}

配置看上去很多,真正和跨域相关的配置只有 .and().cors().configurationSource(corsConfigurationSource()) 一段代码,其中 corsConfigurationSource 方法的配置和 CorsFilter 方式中的相似。

以上就是 SpringBoot 解决跨域问题的方案说明, 在此记录下。

猜你喜欢

转载自blog.csdn.net/qq_29119581/article/details/128730702