【问题标题】:fetch() does not send headers when adding spring security module?添加 spring 安全模块时,fetch() 不发送标头?
【发布时间】:2020-04-21 05:54:18
【问题描述】:

我最近在我的项目中添加了 Spring 安全性(react apollo graphQl / springboot),似乎我无法发送标头??我假设它是 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()
});

弹簧安全配置:

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

开发工具:

看起来标题甚至没有发送!?

有人能解决这个问题吗!我究竟做错了什么 ?

【问题讨论】:

  • 您遇到了 cors 问题吗?是客户端运行的端口是3000,用*试试看是否正常。基本上,您需要在添加 allowedOrigins 的代码中加入白名单,尝试使用 * 并检查其是否有效
  • 是的:从源 'localhost:3000' 获取在 'localhost:8080/graphql' 处的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP好的状态。是的,它在 3000 上运行,我刚刚尝试过 * 仍然是同样的错误
  • 有cors扩展可以安装试试看,预检模式基本上是出于安全考虑
  • 我试过 Access-Control-Allow-Origin Chrome 扩展,还是一样的错误。我什至尝试将浏览器从 chrome 更改为 Firefox 到相同的错误。
  • 这不是浏览器问题,它基本上是服务器端的允许来源,我们需要将请求将发出的域列入白名单

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


【解决方案1】:

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

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

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

有关白名单和避免 cors 问题,请参阅 here

【讨论】:

    猜你喜欢
    • 2018-01-17
    • 2017-02-04
    • 2017-11-27
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2019-05-11
    • 2019-10-11
    • 1970-01-01
    相关资源
    最近更新 更多