我正在尝试使用浏览器的 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 token ,但我不知道如何生成它以将其包含在对后端 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
调用,然后按照解决方案 here 来解决此问题。进行以下添加/更正:
在
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 token 作为名为 “XSRF-TOKEN” 的 cookie 发送回,并从名为 “X-XSRF-TOKEN”的 header 中读取 CSRF token 强>.
关于java - 如何在具有 Spring Boot 后端的 Vue.js 应用程序中包含 CSRF token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60265617/