【发布时间】:2021-12-03 03:30:27
【问题描述】:
-
我有一个在默认配置中启用了 Spring Security 的 SpringBoot 后端(那里没有改变)。
-
我有以下 Rest Controller 和 Post Mapping:
@RestController
public class MyController {
@PostMapping(value = "/sm/resrc/pth")
public Integer postSomething(@RequestParam String someValue,@RequestParam String userId){
System.out.println(String.format("SomeValue: %s from userid %s",someValue,userId));
return 0;
}
}
- 从以下表单创建 Post 请求可以正常工作:
<form method="post" th:action="@{/sm/resrc/pth}">
<input type="text" name="someValue">
<input type="text" name="userId">
<input type="hidden" name="_csrf" value="${_csrf.token}" />
<div><input type="submit" value="Send" /></div>
</form>
它甚至可以在没有隐藏 cors 值的情况下工作。
- 但是我需要从 JavaScript 创建一个 post 请求,这不起作用。 SpringBoot 应用程序在 localhost:8080 运行。我想,credentials 参数 'include' 用于包含所需的身份验证标头,用户已经成功输入这些标头以打开给定页面。它是否正确?我还更改了 'mode' 的值。我尝试了 'cors'、'same-origin' 和 'no-cors'。它只是行不通。我事件不明白为什么 cors 是一个问题,因为我正在请求来自同一来源的资源。在不使用凭证参数的情况下手动将授权标头添加到请求后,它甚至都不起作用。如图所示,我总是得到 403 状态。我的请求有什么问题?我错过了什么?
let data = {
"some":"abc",
"values":this.localDescription,
"userId":userId
};
fetch("sm/resrc/pth",
{
method: 'POST',
credentials: 'include',
mode: 'cors',
body: data
}
).then(response => console.log(response));
【问题讨论】:
标签: javascript spring authentication fetch-api