fetch() 在添加 spring 安全模块时不发送 headers?
fetch() does not send headers when adding spring security module?
我最近为我的项目添加了 Spring 安全性(react apollo graphQl / springboot),但我似乎无法发送 headers ??我假设它是 CORS。
我的代码使用 apollo-client 进行反应:
const httpLink = new HttpLink({ uri: 'http://localhost:8080/graphql' });
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
});
return forward(operation);
});
export const clientBackEnd = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
spring 安全配置:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable()
.authorizeRequests().antMatchers("/authenticate").permitAll().
anyRequest().authenticated().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
Cors 配置:
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/graphql").allowedOrigins("http://localhost:3000", "http://localhost:3001");
}
};
}
}
开发工具:
看起来 headers 甚至都没有发送!?
有人能解决这个问题吗!我究竟做错了什么 ?
正如在进一步评论中所讨论的,该问题是基于将生成请求的来源列入白名单。
所以问题基本上是 - 我们需要通过将请求即将到来或发起的域列入白名单来允许服务器端的来源
所以这里客户端运行在 3000,所以当它请求数据时,我们需要将该端口列入白名单并返回响应
关于白名单和避免cors问题参考
我最近为我的项目添加了 Spring 安全性(react apollo graphQl / springboot),但我似乎无法发送 headers ??我假设它是 CORS。
我的代码使用 apollo-client 进行反应:
const httpLink = new HttpLink({ uri: 'http://localhost:8080/graphql' });
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
});
return forward(operation);
});
export const clientBackEnd = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
spring 安全配置:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable()
.authorizeRequests().antMatchers("/authenticate").permitAll().
anyRequest().authenticated().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
Cors 配置:
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/graphql").allowedOrigins("http://localhost:3000", "http://localhost:3001");
}
};
}
}
开发工具:
看起来 headers 甚至都没有发送!?
有人能解决这个问题吗!我究竟做错了什么 ?
正如在进一步评论中所讨论的,该问题是基于将生成请求的来源列入白名单。
所以问题基本上是 - 我们需要通过将请求即将到来或发起的域列入白名单来允许服务器端的来源
所以这里客户端运行在 3000,所以当它请求数据时,我们需要将该端口列入白名单并返回响应
关于白名单和避免cors问题参考