添加spring安全模块时,fetch()不发送标头吗?

时间:2020-01-02 15:03:38

标签: reactjs spring-boot cors graphql react-apollo

我最近将Spring安全性添加到了我的项目中(react apollo graphQl / springboot),似乎我无法发送标头?我认为是CORS。

我的代码使用apollo-client REACT:

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");
            }
        };
    }
}

devtools:

看起来甚至没有发送标题! enter image description here

可以弄清楚这个问题!我究竟做错了什么 ?

1 个答案:

答案 0 :(得分:0)

正如在进一步的评论中讨论的那样,该问题是基于将请求生成的来源列入白名单。

所以问题基本上是-我们需要通过将请求将要发出或发出请求的域列入白名单来允许服务器端的起源

所以这里的客户端运行在3000,所以当它要求数据时,我们需要将该端口列入白名单并返回响应

有关将其列入白名单并避免cors问题的信息,请参见here

相关问题