Reactjs React fetch响应缺少授权标头
我对CORS使用React fetch和Spring Boot有一些问题 React应用程序在localhost:3000上运行 Spring引导后端在本地主机3001上运行 我的问题是,当我尝试使用带有url的fetch登录时,javascript中的响应不包含授权令牌 后端端的身份验证工作正常 当我打开Chrome Inspector时,我可以在登录请求的网络选项卡中看到授权,只是javascript响应中缺少授权 React fetch请求如下所示:在代码中,const userToken=response.headers.get('Authorization');返回“null”字符串而不是令牌Reactjs React fetch响应缺少授权标头,reactjs,spring-boot,spring-security,cors,fetch-api,Reactjs,Spring Boot,Spring Security,Cors,Fetch Api,我对CORS使用React fetch和Spring Boot有一些问题 React应用程序在localhost:3000上运行 Spring引导后端在本地主机3001上运行 我的问题是,当我尝试使用带有url的fetch登录时,javascript中的响应不包含授权令牌 后端端的身份验证工作正常 当我打开Chrome Inspector时,我可以在登录请求的网络选项卡中看到授权,只是javascript响应中缺少授权 React fetch请求如下所示:在代码中,const userToken
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引导安全配置如下所示:
@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:“”时,登录成功,上面的React代码可以读取授权头。但是我不想使用代理。您可以尝试
curl
Spring安全端点,或者使用Postman并将结果Http响应添加到您的问题中吗?有效的curl命令可以如下所示:curl-i-XPOST-H'内容类型:application/json'-d'{“email”:“youremail”、“password”、“yourpassword”}http://localhost:3001/login
您需要让Spring代码发送Access Control Expose Headers响应标头,其值中包含授权。再见,谢谢!这是添加Access Control Expose Headers响应头的解决方案,需要允许输入请求类型GET、POST、OPTIONS和请求头处理其他请求。