【发布时间】: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