Spring Boot3 跨域配置 Cors的方式

 更新时间:2024年01月15日 09:01:18   作者:Code技术分享  
这篇文章主要介绍了Spring Boot3 跨域配置 Cors,通过使用CORS,开发人员可以控制哪些外部网页可以访问他们的资源,从而提高应用程序的安全性,本文结合实例代码给大家介绍的非常详细,需要的朋友可以参考下

什么是CORS?

CORS,全称是“跨源资源共享”(Cross-Origin Resource Sharing),是一种Web应用程序的安全机制,用于控制不同源的资源之间的交互。

在Web应用程序中,CORS定义了一种机制,通过该机制,浏览器能够限制哪些外部网页可以访问来自不同源的资源。源由协议、域名和端口组成。当一个网页请求另一个网页上的资源时,浏览器会检查请求是否符合CORS规范,以确定是否允许该请求。

CORS的工作原理是:当浏览器发送一个跨域请求时,它会附加一些额外的头部信息到请求中,这些头部信息包含了关于请求的来源和目的的信息。服务器可以检查这些头部信息并决定是否允许该请求。如果服务器允许请求,它会返回一个响应,其中包含一个名为“Access-Control-Allow-Origin”的头部信息,该信息指定了哪些源可以访问该资源。浏览器会检查返回的“Access-Control-Allow-Origin”头部信息,以确定是否允许该跨域请求。

通过使用CORS,开发人员可以控制哪些外部网页可以访问他们的资源,从而提高应用程序的安全性。

Spring Boot 如何配置CORS?

Spring Boot对于跨域请求的支持可以通过两种配置方式来实现:

  • 注解配置:可以使用@CrossOrigin注解来启用CORS。例如,在需要支持跨域请求的方法上添加@CrossOrigin注解,并配置好origins和maxAge等参数。
  • 全局配置:可以通过实现WebMvcConfigurer接口并注册一个WebMvcConfigurer bean来配置CORS的全局设置。在实现类中覆盖addCorsMappings方法,通过CorsRegistry对象添加映射规则。默认情况下,所有方法都支持跨域,并且GET、POST和HEAD请求是被允许的。如果需要自定义,可以配置CorsRegistry对象来指定允许的域名、端口和请求方法等。
  • 过滤器配置:可以通过CorsFilter bean来配置CORS的过滤器。这种方式可以更加灵活地控制CORS的配置,例如只允许特定的域名进行跨域访问等。

前端代码

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    </head>
    <body>
        <script>
            $.ajax({
                url: 'http://localhost:8080/hello',
                type: 'GET',
                //xhrFields: { withCredentials: true }, //开启认证
                success: function (data) {
                    console.log(data)
                }
            })
        </script>
    </body>
</html>

注解配置

@CrossOrigin 是 Spring Framework 中的一个注解,用于处理跨域请求。当一个前端页面尝试从不同的源(域名、端口或协议)请求数据时,浏览器的同源策略会阻止这种请求,以防止潜在的安全问题。然而,在某些情况下,你可能希望允许跨域请求,这时就可以使用 @CrossOrigin 注解。

添加CorssOrigin注解

package com.mcode.springbootcorsdemo.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * ClassName: HelloController
 * Package: com.mcode.springbootcorsdemo.controller
 * Description:
 *
 * @Author: robin
 * @Version: v1.0
 */
@RestController
public class HelloController {
    @CrossOrigin(value = "http://127.0.0.1:5500",allowedHeaders = "*",allowCredentials = "true")
    @GetMapping("/hello")
    public String hello(){
        return "Hello";
    }
}

属性:

@CrossOrigin 注解有几个属性,允许你更精细地控制跨域行为:

* origins: 允许的源列表,可以是域名、IP 或其他标识符。多个源可以使用逗号分隔。  
* methods: 允许的 HTTP 方法列表。例如,只允许 GET 请求。  
* allowedHeaders: 允许的请求头列表。默认情况下,允许所有请求头。  
* allowCredentials:是否允许配置;值为true、false的字符串
* maxAge: 预检请求的缓存时间(以秒为单位)。默认是 86400 秒(24小时)。这些属性可以根据需要进行组合和配置。
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin {
    @AliasFor("origins")
    String[] value() default {};
    @AliasFor("value")
    String[] origins() default {};
    String[] originPatterns() default {};
    String[] allowedHeaders() default {};
    String[] exposedHeaders() default {};
    RequestMethod[] methods() default {};
    String allowCredentials() default "";
    long maxAge() default -1L;
}

全局配置

addCorsMappings 是 Spring Boot 中用于配置跨域请求的方法。它允许你指定哪些路径的请求需要进行跨域处理,以及如何处理这些请求。

在 addCorsMappings 方法中,你可以使用 addMapping 方法来指定需要跨域处理的请求路径。例如:

package com.mcode.springbootcorsdemo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
 * ClassName: MyWebMvcConfigurer
 * Package: com.mcode.springbootcorsdemo.config
 * Description:
 *
 * @Author: robin
 * @Version: v1.0
 */
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 允许所有请求路径跨域访问
                .allowCredentials(true) // 是否携带Cookie,默认false
                .allowedHeaders("*") // 允许的请求头类型
                .maxAge(3600)  // 预检请求的缓存时间(单位:秒)
                .allowedMethods("*") // 允许的请求方法类型
                .allowedOrigins("http://127.0.0.1:5500"); // 允许哪些域名进行跨域访问
    }
}

过滤器配置

在Spring Boot中,CorsFilter用于处理跨域请求。它是一个过滤器,用于在Spring应用程序中启用CORS(跨源资源共享)支持。

package com.mcode.springbootcorsdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
 * ClassName: CorsConfig
 * Package: com.mcode.springbootcorsdemo.config
 * Description:
 *
 * @Author: robin
 * @Version: v1.0
 */
@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter(){
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.addAllowedOrigin("http://127.0.0.1:5500");
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",config);
        return  new CorsFilter(source);
    }
}

注意事项

当我们没有配置跨域的时候会提示:

Access to XMLHttpRequest at 'http://localhost:8080/hello' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

当我们开启withCredentials:true的时候没有配置allowCredentials为true会提示:

Access to XMLHttpRequest at 'http://localhost:8080/hello' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

当我们在后端配置了allowCredentials(true)那么就不能配置allowedOrigins("*"),必须指定来源

jakarta.servlet.ServletException: Request processing failed: java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.

到此这篇关于Spring Boot3 跨域配置 Cors的文章就介绍到这了,更多相关Spring Boot3 跨域配置 Cors内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java的垃圾回收机制实例分析

    Java的垃圾回收机制实例分析

    这篇文章主要介绍了Java的垃圾回收机制,结合实例形式分析了垃圾回收机制的原理及相关操作技巧,需要的朋友可以参考下
    2019-08-08
  • Java中ThreadLocal的使用

    Java中ThreadLocal的使用

    这篇文章主要介绍了Java中ThreadLocal的使用,静态内部类的加载是在程序中调用静态内部类的时候加载的,和外部类的加载没有必然关系, 但是在加载静态内部类的时候 发现外部类还没有加载,那么就会先加载外部类 ,加载完外部类之后,再加载静态内部类,需要的朋友可以参考下
    2023-09-09
  • Springboot中项目的属性配置的详细介绍

    Springboot中项目的属性配置的详细介绍

    很多时候需要用到一些配置的信息,这些信息可能在测试环境和生产环境下会有不同的配置,本文主要介绍了Springboot中项目的属性配置的详细介绍,感兴趣的可以了解一下
    2022-01-01
  • Java中缀表达式转后缀表达式实现方法详解

    Java中缀表达式转后缀表达式实现方法详解

    这篇文章主要介绍了Java中缀表达式转后缀表达式实现方法,结合实例形式分析了Java中缀表达式转换成后缀表达式的相关算法原理与具体实现技巧,需要的朋友可以参考下
    2019-03-03
  • Mybatis的动态Sql组合模式详情

    Mybatis的动态Sql组合模式详情

    这篇文章主要介绍了Mybatis的动态Sql组合模式详情,这篇文章从组合模式的角度分析了Mybatis动态sql的部分,SqlNode是组合模式的Component接口,更多相关内容需要的小伙伴可以参考一下
    2022-08-08
  • Java基础将Bean属性值放入Map中的实例

    Java基础将Bean属性值放入Map中的实例

    这篇文章主要介绍了Java基础将Bean属性值放入Map中的实例的相关资料,需要的朋友可以参考下
    2017-07-07
  • Spring Boot 中使用cache缓存的方法

    Spring Boot 中使用cache缓存的方法

    Spring Cache是Spring针对Spring应用,给出的一整套应用缓存解决方案。下面小编给大家带来了Spring Boot 中使用cache缓存的方法,感兴趣的朋友参考下吧
    2018-01-01
  • @Configuration与@Component作为配置类的区别详解

    @Configuration与@Component作为配置类的区别详解

    这篇文章主要介绍了@Configuration与@Component作为配置类的区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-06-06
  • Java的堵塞队列BlockingQueue详解

    Java的堵塞队列BlockingQueue详解

    这篇文章主要介绍了Java的堵塞队列BlockingQueue详解,阻塞队列常用于生产者和消费者的场景,生产者是向队列里添加元素的线程,消费者是从队列里取元素的线程,需要的朋友可以参考下
    2023-12-12
  • 2种Java删除ArrayList中的重复元素的方法

    2种Java删除ArrayList中的重复元素的方法

    这篇文章主要介绍了2种Java删除ArrayList中的重复元素的方法,感兴趣的朋友可以参考下
    2015-08-08

最新评论