跨域是怎么来的呢?跨域是由同源策略引起的。同源策略(Sameoriginpolicy)是一种约定。它是浏览器最核心、最基本的安全功能。设备的正常功能可能会受到影响。可以说Web是建立在同源策略的基础上的,而浏览器只是同源策略的一种实现。*同源策略,这是Netscape提出的一个著名的安全策略。*所有支持JavaScript的浏览器现在都使用这个策略。*所谓同源,就是域名、协议、端口相同。*当浏览器的两个标签页分别打开来自百度和谷歌的页面时*当浏览器的百度标签页执行脚本时,会检查脚本属于哪个页面,*即检查是否同源,only只会执行与百度同源的脚本。*如果来源不一样,在请求数据时,浏览器会在控制台报异常,提示访问被拒绝。通过nginx代理nginx可以轻松解决跨域中心化的解决方案。本题重点介绍SpringSecurity的解决方案,通过服务器处理,通过Controller添加注解@CrossOrigin。这种方法比较麻烦,每个Controller都需要使用这个注解,比如一些隐式接口(jar包提供)不能使用注解导入org.springframework.context.annotation.Bean;导入org.springframework.context.annotation。Configuration;通过安全配置接口导入org.springframework.web.cors.CorsConfiguration){CorsConfigurationcorsConfiguration=newCorsConfiguration.Allows();corsConfiguration.addAllowedOrigin("*");corsConfiguration.addAllowedHeader("*");corsConfiguration.addAllowedMethod("*");UrlBasedCorsConfigurationSourceurlBasedCorsConfigurationSource=newUrlBasedCorsConfigurationSource();urlBasedCorsConfigurationSource.register("/**Cors,cors配置);返回新的CorsFilter(urlBasedCorsConfigurationSource);}}@Configuration@EnableResourceServer@EnableGlobalMethodSecurity(prePostEnabled=true)publicclassResourceServerConfigurationextendsResourceServerConfigurerAdapter{//注册登录业务处理@AutowiredprivateLoginAuthenticationFilterloginAuthenticationFilter;@Overridepublicvoidconfigure(HttpSecurityhttp)throwsException{http//跨域配置开始.cors().disable().cors().and().authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll()//跨域配置绑定.and().addFilterBefore(loginAuthenticationFilter,UsernamePasswordAuthenticationFilter.class).sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and().requestMatchers().anyRequest().and().anonymous().and().authorizeRequests().antMatchers("/swagger/**","/v2/api-docs","/doc.html","/swagger-ui.html","/swagger-resources/**").permitAll().and().authorizeRequests().antMatchers("/**").authenticated();//配置所有权限控件,必须先认证才能访问}}
