Spring项目-跨域验证与解决

1 说明

        前后端分离项目中,跨域问题不可避免。往往发生的情况是,后端开发验证接口没有问题,前端小伙伴说接口报跨域了。后端开发一般都是通过自带的Swagger在线文档或Postman验证接口的,这两个工具,没有跨域问题,所以误导了后端开发人员。

2 跨域验证

2.1 html代码

        提供一段html代码,便于后端开发自行验证接口。

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <title>Http跨域请求示例</title>
</head>
<style>
    body {
        -moz-backgroud-size: 100% 100%;
        background-size: 100% 100%;
        background-repeat: no-repeat;
    }

    input {
        -web-kit-appearance: none;
        -moz-appearance: none;
        margin-top: 10px;
        font-size: 1.2em;
        width: 50%;
        height: 2.0em;
        border-radius: 10px;
        border: 2px solid;
        color: #6a6f77;
        outline: 0;
        padding: 2px 10px;
    }

    /* 此处内部样式覆盖外部样式 */
    .main {
        margin: 5% 10%;
        overflow: hidden;
    }

    .top {
        text-align: left;
        background-color: #b5c4b1;
        width: 100%;
        padding: 15px;
    }


    .down {
        text-align: left;
        background-color: #b5c4b1;
        width: 100%;
        padding: 15px;
    }

    .title {
        color: #000000;
        font-size: 20px;
        font-style: normal;
        font-weight: bold;
    }

    .show-text {
        border: none;
        margin-top: 20px;
        width: 96%;
        border-radius: 5px;
        background-color: #dadad8;
        color: #222222;
        height: 5.0em;
        font-size: 15px;
    }

    .button1 {
        border: none;
        padding: 5px 15px;
        margin-left: 10px;
        height: 2.0em;
        border-radius: 10px;
        background-color: #1F7BFF;
        color: #ffffff;
        font-size: 1.2em;
    }

    .button1:active {
        background-color: #076af5;
        color: #eeeeee;
    }

    .button2 {
        border: none;
        margin-top: 5px;
        padding: 5px 15px;
        height: 2.0em;
        width: 96%;
        border-radius: 10px;
        background-color: #a6a6a8;
        color: #ffffff;
        font-size: 1.2em;
    }

    .button2:active {
        background-color: #9e9eaa;
        color: #f8f8f8;
    }
</style>

<body>

    <div class="main">
        <div class="top">
            <div class="title">Get请求</div>
            <div class="line">
                <input id="en_input_id1" placeholder="请输入Url" />
                <button id="en_btn_id2" class="button1" onclick="httpGet()">请求</buttondiv>
            </div>

            <textarea id="en_div_4" class="show-text">Get请求结果...</textarea>

            <button id="en_btn_id5" class="button2" onclick="httpGetCopy()">复制结果</button>
        </div>

        <script>
            function httpGet() {
                x = document.getElementById("en_input_id1");
                y = document.getElementById("en_div_4");

                $.ajax({
                    url: x.value,
                    dataType: "json",
                    type: "get",
                    headers: {
                        "Content-Type": "application/json;charset=UTF-8",
                        // 'Authorization': "Bearer xxxxxxx",
                    },
                    data: {
                        // key: "7486e10d3ca83a934438176cf941df0c",
                    },
                    success: function (res) {
                        y.innerHTML = JSON.stringify(res);
                        console.log(res);  //在console中查看数据
                    },
                    error: function (res) {
                        y.innerHTML = JSON.stringify(res);
                        // alert('failed!');
                    },
                });
            }

            function httpGetCopy() {
                    console.log("httpGetCopy")
                    y = document.getElementById("en_div_4");

                    const el = document.createElement('input');
                    // 给input元素赋值需要复制的文本
                    el.setAttribute('value', y.innerHTML);
                    // 将input元素插入页面
                    document.body.appendChild(el);
                    // 选中input元素的文本
                    el.select();
                    // 复制内容到剪贴板
                    document.execCommand('copy');
                    // 删除input元素
                    document.body.removeChild(el);

                    alert("已复制");
                }
        </script>

        <br>

        <div class="down">
            <div class="title">Post请求</div>

            <div class="line">
                <input id="de_input_id1" placeholder="请输入Url" />
                <input id="de_input_id2" placeholder="请输入Body,Json格式(可不填)" />
                <button id="de_btn_id2" class="button1" onclick="httpPost()">请求</buttondiv>
            </div>

            <textarea id="de_div_5" class="show-text">Post结果...</textarea>

            <button id="de_btn_id5" class="button2" onclick="httpPostCopy()">复制结果</button>
        </div>

        <script>
            function httpPost() {
                x1 = document.getElementById("de_input_id1");
                x2 = document.getElementById("de_input_id2");

                y = document.getElementById("de_div_5");

                $.ajax({
                    url: x1.value,
                    dataType: "json",
                    type: "POST",
                    headers: {
                        "Content-Type": "application/json;charset=UTF-8",
                    },
                    data: x2.value == "" ? {} : x2.value,
                    success: function (res) {
                        y.innerHTML = JSON.stringify(res);
                        console.log(res);  //在console中查看数据
                    },
                    error: function (res) {
                        y.innerHTML = JSON.stringify(res);
                        // alert('failed!');
                    },
                });
            }


            function httpPostCopy() {
                y = document.getElementById("de_div_5");

                const el = document.createElement('input');
                // 给input元素赋值需要复制的文本
                el.setAttribute('value', y.innerHTML);
                // 将input元素插入页面
                document.body.appendChild(el);
                // 选中input元素的文本
                el.select();
                // 复制内容到剪贴板
                document.execCommand('copy');
                // 删除input元素
                document.body.removeChild(el);

                alert("已复制");
            }
        </script>

    </div>


</body>

</html>

2.2 验证

        (1) 有跨域问题

 

   

        (2) 跨域问题已解决

 

3 后端解决跨域问题

        Spring不同版本处理方式有所不同,固提供两种方法,如下所示。

        (1) Spring2.4之前的版本

package com.digital.art.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;

/**
 * @author SSM
 * @description 对于spring security oauth2 默认接口,例如 /oauth/token 跨域问题,可以通过全局 CORS Filter 解决
 * @date 2019/12/25 10:46
 */
@Configuration
public class GlobalCorsConfiguration {


	@Bean
	public CorsFilter corsFilter() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.setAllowCredentials(true);
		corsConfiguration.addAllowedOrigin("*");
//		corsConfiguration.setAllowedOrigins(Arrays.asList(orgins));
		corsConfiguration.addAllowedHeader("*");
		corsConfiguration.addAllowedMethod("*");
		UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
		urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
		return new CorsFilter(urlBasedCorsConfigurationSource);
	}

}

        (2) Spring2.4之后的版本

package com.module.nacos.pay.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.*;

import java.util.List;

/**
 * @ClassName WebConfig
 * @Description 
 * @Author ssm
 * @Date 2020/7/9 11:03
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {


    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

    }

    // SpringBoot2.4.0 [allowedOriginPatterns]代替[allowedOrigins]
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .maxAge(3600)
                .allowCredentials(true);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /**
         * 支持swagger
         */
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        /**
         * 支持webjars
         */
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

        /**
         * templates模板
         */
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/templates/**")
                .addResourceLocations("classpath:/templates/");
    }
}

4 参考链接

(1) 跨源资源共享(CORS) - HTTP | MDN

(2) jQuery的Ajax实例(附完整代码)_Yuan_mingyu的博客-CSDN博客_jquery ajax

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Security 是一个基于 Spring 的安全框架,主要用于为 Java Web 应用程序提供身份验证和授权功能。而跨域请求通常是指在浏览器环境下,前端页面使用 AJAX 发起跨域请求,而后端服务器需要响应跨域请求的场景。 Spring Security 提供了解决跨域请求的方式,其中比较常用的是 CORS(跨域资源共享)机制。CORS 机制通过在服务器端设置响应头来允许跨域访问,具体步骤如下: 1. 在 Spring Security 的配置中添加 cors() 方法,如下: ``` @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors() .and() //其他配置 .csrf().disable(); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.addAllowedOrigin("*"); configuration.addAllowedHeader("*"); configuration.addAllowedMethod("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } } ``` 2. 在 CorsConfigurationSource 中设置允许跨域访问的源、方法和头信息。以上代码中的 configuration.addAllowedOrigin("*") 表示允许所有来源跨域访问,configuration.addAllowedHeader("*") 表示允许所有头信息,configuration.addAllowedMethod("*") 表示允许所有 HTTP 方法。 以上就是 Spring Security 解决跨域请求的方法,希望对您有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卡卡木樨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值