javascript - 如何将“Access-Control-Expose-Headers”添加到 POST /login 端点?
问题描述
X-Auth-Token
我的目标是使用 JavaScript获取标题。
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let formData = new FormData();
formData.append("username", username);
formData.append("password", password);
fetch("/login, {
method: "POST",
redirect: "manual",
body: formData,
})
.then(response => console.log(response.headers));
我的预期结果是:response.headers
包含X-Auth-Token
键和值。
我的实际结果是:response.headers
是空的。我检查了浏览器的检查工具Ctrl+Shift+I
> 网络 > 登录,响应标头有X-Auth-Token
标头。
我试过的
- 在里面创建 bean corsConfigurationSource
public class WebSecurityConfig extends WebSecurityConfigurer
@Bean CorsConfigurationSource corsConfigurationSource {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setExposedHeaders(Collections.singletonList("X-Auth-Token"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
我使用 Postman 和浏览器的检查工具来查看响应标头,但它不包含Access-Control-Expose-Headers
标头。response.headers
还是空的。
编辑
我添加了 bean@EnableWebSecurity
和 Override configure(HttpSecurity http)
。
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.cors()
.and()
.formLogin()
.and()
.authorizeRequests()
.antMatchers("/chat").permitAll()
.anyRequest().authenticated();
}
// TODO: vulnerability test.
// require:
// 1. Add a bean with @EnableWebSecurity
// 2. Override configure(HttpSecurity http) http.cors()
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Collections.singletonList("*"));
config.setAllowedMethods(Collections.singletonList("*"));
config.setExposedHeaders(Collections.singletonList("X-Auth-Token"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}
Origin: http://localhost:3000
然后,我将请求从带有 FormData 正文的端点发送到 POST /login 。问题仍然存在,尽管存在标头和标头,但我仍然无法获取X-Auth-Token
标头的值。Access-Control-Expose-Headers
X-Auth-Token
解决方案
推荐阅读
- xcode - Xcode 12 中的类型检查错误:“编译器无法在合理的时间内对该表达式进行类型检查”
- laravel - 测试 E2E Cypress Laravel Jetstream 失败点击
- java - 如何在 JAVA 中将此以下 CURL 更改为 REST 客户端?
- javascript - 未捕获的错误:Reference.set 失败:第一个参数在属性“Users.ji8A7TkSldfdvieDqGxko9eV3Jy1.gender”中包含未定义
- sql - 计算另一列中某个值出现次数的存储过程
- python - 多个字段包括用 python 和 mysql 排除
- arrays - VBA 数组函数的工作速度比 vlookup 慢
- tarantool - 如何向现有索引添加新字段?
- list - 我想在颤振中为购物应用程序制作类别页面?
- python - 与anaconda的包冲突