简体   繁体   English

如何在Spring Boot Cors中设置标头?

[英]How do I set header in spring boot cors?

I want to enable CORS in spring boot 2. I've done this as follows: 我想在Spring Boot 2中启用CORS。我这样做如下:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*");
    }
}

This work fine in most requests, but in some special request I need to set Access-Control-Allow-Origin header in response. 在大多数请求中都可以正常工作,但是在某些特殊请求中,我需要设置Access-Control-Allow-Origin标头作为响应。 How can I do it ? 我该怎么

There are many Ways to do this like using Filter or Interceptor or Aspects. 有许多方法可以做到这一点,例如使用“过滤器”或“拦截器”或“方面”。 You can also use WebFilter if you are using Spring 5. 如果使用Spring 5,也可以使用WebFilter。

One of the ways to do so is through Interceptors. 其中一种方法是通过拦截器。 Here is a rough code. 这是一个粗略的代码。

public class AccessControlInterceptor implements HandlerInterceptor {

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(somecondition) {
            response.setHeader("Access-Control-Allow-Origin", "your_value");
        }
    }
}

And register this Interceptor with spring like this 并用这样的弹簧注册这个拦截器

@Configuration
public class MyConfig extends WebMvcConfigurerAdapter{
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(new AccessControlInterceptor ()).addPathPatterns("/**");
    }
}

From Spring documentation https://spring.io/guides/gs/rest-service-cors/ 从Spring文档https://spring.io/guides/gs/rest-service-cors/

Enabling CORS Controller method CORS configuration So that the RESTful web service will include CORS access control headers in its response, you just have to add a @CrossOrigin annotation to the handler method: 启用CORS控制器方法CORS配置 ,以便RESTful Web服务将在其响应中包括CORS访问控制标头,您只需向处理程序方法添加@CrossOrigin批注:

@RestController
public class GreetingController {

    @CrossOrigin(origins = "http://localhost:9000")
    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
        System.out.println("==== in greeting ====");
        return new Greeting(counter.incrementAndGet(),String.format(template, name));
}

This @CrossOrigin annotation enables cross-origin requests only for this specific method. 此@CrossOrigin批注仅针对此特定方法启用跨域请求。 By default, its allows all origins, all headers, the HTTP methods specified in the @RequestMapping annotation and a maxAge of 30 minutes is used. 默认情况下,它允许使用所有来源,所有标头,@ RequestMapping批注中指定的HTTP方法以及30分钟的maxAge。 You can customize this behavior by specifying the value of one of the annotation attributes: origins, methods, allowedHeaders, exposedHeaders, allowCredentials or maxAge. 您可以通过指定以下注释属性之一的值来自定义此行为:起点,方法,allowedHeaders,暴露的Headers,allowCredentials或maxAge。 In this example, we only allow http://localhost:9000 to send cross-origin requests. 在此示例中,我们仅允许http:// localhost:9000发送跨域请求。

it is also possible to add this annotation at controller class level as well, in order to enable CORS on all handler methods of this class. 也可以在控制器类级别添加此批注,以便在此类的所有处理程序方法上启用CORS。

Currently you are setting Access-Control-Allow-Origin to * which is a wildcard and matches all origins. 当前,您正在将Access-Control-Allow-Origin* ,这是一个通配符并匹配所有来源。

If your request contains credential related data, eg by setting XMLHttpRequest.withCredentials to true : 如果您的请求包含与凭据相关的数据,例如通过将XMLHttpRequest.withCredentials设置为true

  • Access-Control-Allow-Origin mustn't have the value * Access-Control-Allow-Origin不得具有值*

  • An additional response header Access-Control-Allow-Credentials with the value true is expected. 期望值为true的附加响应标头Access-Control-Allow-Credentials

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 弹簧启动的CORS不在响应头中 - CORS for spring boot not in response header 如何在Spring Boot中在index.html上设置cookie或标头 - How do i set a cookie or a header on index.html in Spring Boot 如何删除 Kafka(Spring-boot)中的标头? - How do I remove the header in a Kafka (Spring-boot)? 如何在 Spring 引导 Oauth2 资源服务器中使用密码授予处理 CORS - How do I handle CORS in Spring Boot Oauth2 Resource Server with password grant 如何设置可执行的Spring Boot jarfile的JVM属性? - How do I set the JVM properties of an executable Spring Boot jarfile? 如何使用 Spring Boot 设置 Jackson 的 constructorDetector? - How do I set Jackson's constructorDetector with Spring Boot? 如何使用 Spring Boot 设置自定义登录? - How do I set up a custom login with Spring Boot? 如何使用 Spring Boot RestTemplate 将 Microsoft Office Mime 类型作为 Content-Type header 发送 - How do I send Microsoft Office Mime Types as Content-Type header with with Spring Boot RestTemplate 如何在 spring 启动中的 header 中设置文件大小以显示下载进度? - How to set file size in the header in spring boot to display the download progress? 如何在Spring Boot的请求中设置添加新的标题 - How to set add a new Header in Request in Spring Boot
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM