广告
返回顶部
首页 > 资讯 > 服务器 >跨域(CORS)问题的解决方案分享
  • 374
分享到

跨域(CORS)问题的解决方案分享

摘要

目录前后端分离项目,如何解决跨域问题什么是跨域问题跨域问题演示及解决点击前端登录按钮覆盖默认的CorsFilter来解决该问题重新运行代码,点击登录按钮设置springSecurit

前后端分离项目,如何解决跨域问题

跨域资源共享(CORS)是前后端分离项目很常见的问题,本文主要介绍当SpringBoot应用整合SpringSecurity以后如何解决该问题。

什么是跨域问题

CORS全称Cross-Origin Resource Sharing,意为跨域资源共享。当一个资源去访问另一个不同域名或者同域名不同端口的资源时,就会发出跨域请求。如果此时另一个资源不允许其进行跨域资源访问,那么访问的那个资源就会遇到跨域问题。

跨域问题演示及解决

我们使用mall项目的源代码来演示一下跨域问题。此时前端代码运行在8090端口上,后端代码运行在8080端口上,由于其域名都是localhost,但是前端和后端运行端口不一致,此时前端访问后端接口时,就会产生跨域问题。

点击前端登录按钮

此时发现调用登录接口时出现跨域问题。

image-20230211174509434

覆盖默认的CorsFilter来解决该问题

添加GlobalCorsConfig配置文件来允许跨域访问。

package com.Macro.mall.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.WEB.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


@Configuration
public class GlobalCorsConfig {

    
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        //允许所有域名进行跨域调用
        config.addAllowedOrigin("*");
        //允许跨越发送cookie
        config.setAllowCredentials(true);
        //放行全部原始头信息
        config.addAllowedHeader("*");
        //允许所有请求方法跨域调用
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.reGISterCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

或者使用这个配置类


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 CorsConfig implements WebMvcConfigurer {

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

}

重新运行代码,点击登录按钮

发现需要登录认证的/admin/info接口的OPTIONS请求无法通过认证,那是因为复杂的跨越请求需要先进行一次OPTIONS请求进行预检,我们的应用整合了SpringSecurity,对OPTIONS请求并没有放开登录认证。

image-20230211174521320

设置SpringSecurity允许OPTIONS请求访问

在SecurityConfig类的configure(httpsecurity HttpSecurity)方法中添加如下代码。

.antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求
.permitAll()

image-20230211174839138

重新运行代码,点击登录按钮

发现已经可以正常访问。

image-20230211174852577

一次完整的跨域请求

先发起一次OPTIONS请求进行预检

  • 请求头信息:
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Origin: http://localhost:8090
Referer: http://localhost:8090/
User-Agent: Mozilla/5.0 (windows NT 10.0; Win64; x64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/75.0.3770.142 Safari/537.36
  • 响应头信息:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: http://localhost:8090
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Sat, 27 Jul 2019 13:40:32 GMT
Expires: 0
Pragma: no-cache
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
  • 请求成功返回状态码为200

发起真实的跨域请求

  • 请求头信息:
Accept: application/JSON, text/plain
Content-Type: application/json;charset=UTF-8
Origin: http://localhost:8090
Referer: http://localhost:8090/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36
{username: "admin", passWord: "123456"}
password: "123456"
username: "admin"
  • 响应头信息:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8090
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: application/json;charset=UTF-8
Date: Sat, 27 Jul 2019 13:40:32 GMT
Expires: 0
Pragma: no-cache
Transfer-Encoding: chunked
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
  • 请求成功返回状态码为200

到此这篇关于跨域(CORS)问题的解决方案分享的文章就介绍到这了,更多相关解决跨域(CORS)问题内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 跨域(CORS)问题的解决方案分享

本文链接: https://www.lsjlt.com/news/195743.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作