【发布时间】:2016-07-05 02:50:09
【问题描述】:
我正在尝试编写 CORS REST 服务。我的意思是一种 REST 服务,我可以从托管在 Web 服务器上的网站调用该服务,该网站的端口与 REST 服务器不同。
我正在使用 whatwg-fetch(Fetch API 客户端的 polyfill)和 REST 服务的 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);
}
}
上面的代码可以很好地处理 GET 请求,但是 POST 失败。 Access-Control-Allow-Origin 未在对客户端的响应中设置。但是,它是在预检期间为OPTIONS 方法设置的。我无法控制 OPTIONS 和 POST 的发送方式,我只是使用 whatwg-fetch 并执行 POST,然后中间件自己执行 OPTIONS 和 POST。但主要问题是为什么我的 RestController 没有在 POST 请求中以 Access-Control-Allow-Origin 响应?
(我根本没有使用任何授权,POST请求的返回码是403 Forbidden。)
更新!正如我所怀疑的那样,403 Forbidden 与 CORS 无关,而是与 CSRF 相关。 POST 请求中缺少 CSRF 令牌。这是我现在面临的另一个问题:D 应该在 POST 请求中发送的 CSRF 令牌作为 OPTIONS 请求的响应中的标头发送到客户端。当使用whatwg-fetch 时,我无法访问它们,因为whatwg-fetch 处理的是自动预检和POST。 有什么想法吗?
【问题讨论】:
-
来源真的是
localhost? -
还需要添加支持跨域访问的HTTP Verbs(GET,POST...),
标签: rest spring-mvc spring-boot cors