springboot 跨域问题

springboot 跨域问题

概念

什么是跨域访问?

JavaScript出于安全方面的考虑,做了一个同源策略的限制,也就是说不允许跨域访问其他资源,更通俗的说就是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript实施的安全限制。

什么是同源策略?

所谓的同源是指域名、协议、端口均为相同。

同源策略的作用

同源政策的目的是为了防止恶意网站通过冒充用户来窃取用户的数据信息,同源策略提高了攻击成本。

同源策略限制了以下行为:

  • Cookie、LocalStorage 和 IndexDB 无法读取;
  • DOM 和 JS 对象无法获取;
  • Ajax请求发送不出去。

springboot 解决跨域问题

方式1

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SpringMVCConfig implements WebMvcConfigurer {

    //跨域设置
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //针对的映射
        registry.addMapping("/**")
                //针对的origin域名
                .allowedOrigins("*")
                //针对的方法
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                //是否允许发送Cookie
                .allowCredentials(true)
                //从预检请求得到相应的最大时间,默认30分钟
                .maxAge(3600)
                //针对的请求头
                .allowedHeaders("*");
    }

}

方式二

@Configuration
public class CorsConfig{
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}
posted @ 2020-10-20 14:54  刃牙  阅读(228)  评论(0编辑  收藏  举报