赞
踩
目录
域的定义:协议+域名+端口。三者完全相同则为同域,反之有其一不同均为不同域。
跨域是指当前发起请求的域和请求指向的域属于不同域时,该次请求称之为跨域请求。
由于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。
同源策略
同源策略会阻止一个域的javascript脚本和另一个域的内容进行交互。所谓同源就是指在同一个域
非同源限制
1.无法读取非同源页面的Cookie、LocalStorage和IndexedDB
2.无法接触非同源页面的DOM
3.无法向非同源地址发送AJAX请求
其实无论哪种方案,最终目的都是修改响应头,向响应头中添加浏览器所要求的数据,进而实现跨域
定义配置类,添加@Configuration注解,实现WebMvcConfigurer接口,再重写addCorsMappings方法:
- // 请求跨域
- @Configuration
- public class CorsConfig implements WebMvcConfigurer {
- @Override
- public void addCorsMappings(CorsRegistry registry) {
- //添加映射路径
- registry.addMapping("/**")
- //是否发送Cookie
- .allowCredentials(true)
- //设置放行哪些原始域 SpringBoot2.4.4下低版本使用.allowedOrigins("*")
- .allowedOriginPatterns("*")
- //放行哪些请求方式
- .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
- //.allowedMethods("*") //或者放行全部
- //放行哪些原始请求头部信息
- .allowedHeaders("*")
- //暴露哪些原始请求头部信息
- .exposedHeaders("*");
- }
- }
或者也可以返回新CorsFilter(全局跨域)
- @Configuration
- public class GlobalCorsConfig {
- @Bean
- public CorsFilter corsFilter() {
- //1. 添加 CORS配置信息
- CorsConfiguration config = new CorsConfiguration();
- //放行哪些原始域
- config.addAllowedOrigin("*");
- //是否发送 Cookie
- config.setAllowCredentials(true);
- //放行哪些请求方式
- config.addAllowedMethod("*");
- //放行哪些原始请求头部信息
- config.addAllowedHeader("*");
- //暴露哪些头部信息
- config.addExposedHeader("*");
- //2. 添加映射路径
- UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
- corsConfigurationSource.registerCorsConfiguration("/**",config);
- //3. 返回新的CorsFilter
- return new CorsFilter(corsConfigurationSource);
- }
- }
Controller层再需要跨域的类或者方法上加上@CrossOrigin该注解即可。
- @CrossOrigin(origins = "*",maxAge = 3600)
- public class UserController {
- final UserService userService;
-
- @GetMapping("/getOne/{id}")
- public User getOne(@PathVariable("id") Integer id) {
- return userService.getById(id);
- }
也可以粒度更细一点
- @Controller
- @RequestMapping("/hello")
- public class HelloController {
-
- @GetMapping("/")
- @ResponseBody
- //更小的解决跨域 设置只能某些地址访问
- @CrossOrigin(originPatterns = "http://localhost:8080")
- public Map<String, Object> findAll() {
- //返回数据
- return DataSchool.getStudents();
- }
- }
1.编写过滤器
- // 跨域过滤器
- @Component
- public class CORSFilter implements Filter {
-
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- //*号表示对所有请求都允许跨域访问
- HttpServletResponse res = (HttpServletResponse) response;
- res.addHeader("Access-Control-Allow-Credentials", "true");
- res.addHeader("Access-Control-Allow-Origin", "*");
- res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
- res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
- if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
- response.getWriter().println("Success");
- return;
- }
- chain.doFilter(request, response);
- }
-
- @Override
- public void destroy() {
-
- }
-
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
-
- }
- }
2注册过滤器
- @Configuration
- public class CorsConfig {
-
- @Bean
- public CorsFilter corsFilter() {
- CorsConfiguration corsConfiguration = new CorsConfiguration();
- corsConfiguration.addAllowedOrigin("*");
- corsConfiguration.addAllowedHeader("*");
- corsConfiguration.addAllowedMethod("*");
- corsConfiguration.setAllowCredentials(true);
- UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
- urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
- return new CorsFilter(urlBasedCorsConfigurationSource);
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。