Spring Security+ReactJS - 预检请求
我正在开发一个项目,其中 FE 作为 React,BE 作为 Springboot。我正在尝试将 FE 添加到应用程序中。注册后,我尝试登录该应用程序。登录成功后,我们得到JWT Token。为此,我们需要在正文中发送用户名、密码和授权类型,在标头中发送基本身份验证详细信息。当
var postData = {
username: a,
password: b,
grant_type:'c'
};
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
"Accept": "application/json" ,
"Authorization":"Basic" + " " +base64.encode("U" + ":" + "p")
}
};
axios.post('http://localhost:9003/login/token', postData,axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
我运行这个程序时,我收到错误,
Access to XMLHttpRequest at 'http://localhost:9003/login/token' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我的 Spring boot 代码是
@Override
@CrossOrigin(origins = "*", allowedHeaders = "*") public void
configure(HttpSecurity http) throws Exception {
http.cors().and().exceptionHandling() .authenticationEntryPoint( (request,
response, authException) ->
response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
.and().authorizeRequests().antMatchers("/*").authenticated().and().httpBasic();
http.exceptionHandling().authenticationEntryPoint(new
CustomAuthenticationEntryPoint());
}
@Override
@CrossOrigin(origins = "*",allowedHeaders="*")
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.pathMapping("/oauth/token", "/login/token").tokenStore(tokenStore())
.tokenEnhancer(jwtAccessTokenConverter()).authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
有人知道如何解决这个问题吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 MDN 文档,凭证请求的飞行前响应标头应包含一组特定的
Access-Control-Allow-Origin
而不是通配符*
。可以通过扩展WebSecurityConfigurerAdapter
来设置服务的 cors 配置。我们的 spring-boot 项目面临类似的挑战,以下配置帮助克服了 cors 故障
As per MDN docs, the pre-flight response headers for a credentialed request should include a specific set of
Access-Control-Allow-Origin
and not a wild-card*
.The cors config for the service can be setup by extending theWebSecurityConfigurerAdapter
.We faced a similar challenge with our spring-boot project and the following configuration helped overcome the cors failure
下面这个类配置 CORS 策略,它对我有用。我认为你的问题是 @CrossOrigin 应该位于控制器类中。
如果您想要更多配置,请点击此链接 https://spring.io/guides/gs /rest-service-cors/
This class below to config CORS policy it worked for me.And i think your poblem is @CrossOrigin should be located in controller class.
If you want more config follow this link https://spring.io/guides/gs/rest-service-cors/