如何向post/login端点添加“access control expose headers”?

acruukt9  于 2021-07-24  发布在  Java
关注(0)|答案(0)|浏览(232)

我的目标是得到 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和浏览器的inspect工具查看响应头,但它不包含 `Access-Control-Expose-Headers` 标题。这个 `response.headers` 还是空的。

## 编辑

我加了豆子 `@EnableWebSecurity` 和覆盖 `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;

}
}

然后,我将请求发送到post/login from `Origin: http://localhost:3000` 具有formdata主体的终结点。问题仍然存在,我仍然无法得到答案 `X-Auth-Token` 标题的值 `Access-Control-Expose-Headers` 收割台和 `X-Auth-Token` 标题存在。
![](https://i.stack.imgur.com/8cuaj.png)
![](https://i.stack.imgur.com/6DVyS.png)

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题