首页 > 解决方案 > 如何将“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标头。

我试过的

  1. 在里面创建 bean corsConfigurationSourcepublic 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-HeadersX-Auth-Token

在此处输入图像描述

在此处输入图像描述

标签: javascriptspringspring-security

解决方案


推荐阅读