缺少响应提取响应的授权标头

问题描述 投票:2回答:1

我在使用React Fetch和Spring Boot的CORS中遇到一些问题。

React应用程序在localhost:3000上运行。

Spring Boot后端在localhost:3001上运行。

[我的问题是,当我尝试使用带http://localhost:3001/login url的访存登录时,javascript中的响应不包含授权令牌。

后端的身份验证有效。

当我打开Chrome浏览器检查器时,我可以在登录请求的“网络”标签中看到“授权”,只有它在javascript响应中丢失了。

React提取请求如下所示:在代码中,const userToken = response.headers.get('Authorization');返回“空”字符串而不是令牌。

return fetch("http://localhost:3001/login",{
        method: 'post',
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            email,
            password
        })
    })
    .then(
        response => {
            if(response.ok) {
                const userToken = response.headers.get('Authorization');
                return true;
            }
            // Error handling
        }
    );

Spring Boot Security配置类似于以下内容:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .cors()
            .and()
            .csrf()
            .disable().authorizeRequests()
            .antMatchers(HttpMethod.POST, REGISTRATION_URL).permitAll()
            .anyRequest().authenticated()
            .and()
            .addFilter(// Auth Filter)
            .addFilter(// Another auth Filter)
            // this disables session creation on Spring Security
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
    return source;
}

}

另一件事。当我在package.json中使用proxy:“ http://127.0.0.1:3001”时,登录有效并且上面的React代码可以读取Authorization标头。但是我不想使用代理。

reactjs spring-boot spring-security cors fetch-api
1个回答
0
投票

谢谢!这是对我的问题的准确描述,对我的解决方案有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.