简体   繁体   English

在 CORS 期间 Spring-Boot RestController 失败

[英]Spring-Boot RestController fails during CORS

I am trying to write a CORS REST service.我正在尝试编写 CORS REST 服务。 By that I mean a REST service that I can call from a website that is hosted on a web server with just a different port than the REST server.我的意思是 REST 服务,我可以从托管在 Web 服务器上的网站调用该服务,该网站与 REST 服务器的端口不同。

I am using whatwg-fetch (a polyfill for Fetch API client side) and spring-boot for the REST service.我正在为 REST 服务使用 whatwg-fetch(用于 Fetch API 客户端的 polyfill)和 spring-boot。

package se.beta.note.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import se.selenwall.note.domain.Note;
import se.selenwall.note.domain.repository.NoteRepository;

import java.util.List;

@CrossOrigin(origins = "http://localhost:8001")
@RestController
public class NoteController {
    @Autowired
    private NoteRepository repository;

    @RequestMapping("/note")
    public List<Note> getNotes() {
        List<Note> notes = repository.findAll();
        System.out.println(notes);
        return notes;
    }

    @RequestMapping(value = "/note", method = RequestMethod.POST)
    public void saveNote(@RequestBody @Validated Note note) {
        repository.save(note);
    }
}

The code above work great with GET requests, but the POST fails.上面的代码适用于 GET 请求,但 POST 失败。 Access-Control-Allow-Origin isn't set in the response to the client.在对客户端的响应中未设置Access-Control-Allow-Origin But, it is set for the OPTIONS method during preflight.但是,它是在预检期间为OPTIONS方法设置的。 I am not in control over how OPTIONS and POST are sent, I am just using whatwg-fetch and perform a POST, the middleware is then doing the OPTIONS and POST by itself.我无法控制 OPTIONS 和 POST 的发送方式,我只是使用 whatwg-fetch 并执行 POST,然后中间件自己执行 OPTIONS 和 POST。 But the main question is why my RestController isn't responding with Access-Control-Allow-Origin on the POST request?但主要问题是为什么我的 RestController 没有在 POST 请求中响应Access-Control-Allow-Origin

(I am not using any authorization at all, and the return code is 403 Forbidden on the POST request.) (我根本没有使用任何授权,POST 请求的返回码是 403 Forbidden。)

Uppdate!更新! The 403 Forbidden wasn't related to CORS as I suspected but to CSRF. 403 Forbidden 与我怀疑的 CORS 无关,而是与 CSRF 相关。 The CSRF token is missing on the POST request. POST 请求中缺少 CSRF 令牌。 And this is now another issue I'm facing :D The CSRF token that should be sent in the POST request is sent to the client as a header in the response of the OPTIONS request.这现在是我面临的另一个问题:D 应在 POST 请求中发送的 CSRF 令牌作为 OPTIONS 请求响应中的标头发送到客户端。 And when using whatwg-fetch I just can't reach them as whatwg-fetch handledare preflight and POST automatically.当使用 whatwg-fetch 时,我无法访问它们,因为 whatwg-fetch 处理是自动预检和 POST。 Any ideas annons?有什么想法吗?

delete @CrossOrigin anotation in NoteController.class删除@CrossOrigin @CrossOrigin NoteController.class

create SimpleCORSFilter add this code创建SimpleCORSFilter添加此代码

@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Expose-Headers", "Location");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

You need to instruct Spring on how to deal with CORS requests.您需要指示 Spring 如何处理 CORS 请求。 Either using a servlet filter, or using Spring's @CrossOrigin annotation, or the CorsRegistry .使用 servlet 过滤器,或使用 Spring 的@CrossOrigin注释,或CorsRegistry This guide is pretty handy to get you going https://spring.io/guides/gs/rest-service-cors/本指南非常方便让您使用https://spring.io/guides/gs/rest-service-cors/

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM