java - 如何在带有 Spring Boot 后端的 Vue.js 应用程序中包含 CSRF 令牌?
问题描述
我正在尝试使用浏览器的 Fetch API 向我的后端 REST API 发出 POST 请求,如下所示:
submitRegistration() {
const formElement = document.getElementById('register-form');
fetch('http://localhost:8080/register', {
method: 'POST',
body: new FormData(formElement),
});
}
我正在从这个表格中获取数据:
<v-form id="register-form" @submit.prevent="submitRegistration" class="text-center" ref="form" v-model="valid" lazy-validation>
<v-text-field type="text" name="username" v-model="form.username" :counter="25" :rules="usernameRules" label="Username" required></v-text-field>
<v-text-field type="password" name="userPassword" v-model="form.password" :counter="25" :rules="passwordRules" label="Password" required></v-text-field>
<v-text-field type="text" name="userEmail" v-model="form.email" :rules="emailRules" label="E-mail" required></v-text-field>
<v-btn type="submit" text class="primary">Register</v-btn>
</v-form>
但是,作为响应,我的后端服务器收到403 Forbidden。问题是 CSRF 令牌,但我不知道如何生成它以将其包含在对后端 API 的 POST 请求中。
编辑:在 Spring Boot 中,我的 CORS 映射配置如下:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:9000").allowCredentials(true);
}
};
}
我发布这个是因为Response
返回的对象给了我一个 403 状态并且是“cors”类型,即使如果我使用 HttpSecurity 完全禁用 CSRF,错误就会得到解决 -http.csrf().disable();
解决方案
这可以通过GET
首先调用服务器来解决,然后按照此处的解决方案进行以下添加/更正:
在
submitRegistration()
方法中,在顶部添加以下内容:// Do a fetch to GET the XSRF-TOKEN as a cookie fetch('http://localhost:8080/register'); const csrfToken = this.getCookie('XSRF-TOKEN'); const headers = new Headers({ 'X-XSRF-TOKEN': csrfToken });
我们的 POST 请求现在看起来像这样:
fetch('http://localhost:8080/register', { method: 'POST', headers, credentials: 'include', body: new FormData(formElement), })
在后端,我们需要将以下内容添加到我们的覆盖
configure()
方法中:@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); }
这告诉服务器将 CSRF 令牌作为名为 "XSRF-TOKEN" 的 cookie 发回,并从名为"X-XSRF-TOKEN"的标头中读取 CSRF 令牌。
推荐阅读
- angular - 如何在 Angular 中使用 API 的数据动态创建按钮?
- javascript - 函数原型与类原型之间的 JavaScript 区别
- r - R:For循环从多个数据帧中捕获数据
- java - 如何从 corda/corda-zulu-5.0-snapshot 图像创建自定义图像?
- javascript - ReactGridLayout:ReactGridLayout.children[0].x 必须是数字
- javascript - 如何在 Iphone 设备中让我的输入字段在 1 秒后聚焦?
- rest - 使用带有证书的 https Rest API
- r - 收集功能后数据尽可能整齐
- javascript - 表单代码上的颜色更改文本验证问题
- java - 无法使用 poi 数据驱动将多个字符串写入 excel,但我可以通过提及行号和列号来写入每个单元格