CORS:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。

8

我正在尝试将Angular JS 应用程序与后端Spring Boot集成,但是遇到了预检请求不允许重定向的问题。

这是部署在OpenShift上的,我已经通过在控制器方法中添加一些注释来配置启用CORS,从而解决了以下问题:请求没有“Access-Control-Allow-Origin”标头在传入请求中:CORS策略问题。

    @CrossOrigin(allowedHeaders = "*", origins = "*", exposedHeaders = 
        "Access-Control-Allow-Origin", methods = {
          RequestMethod.POST, RequestMethod.GET, RequestMethod.PUT, 
    RequestMethod.DELETE, RequestMethod.HEAD,
          RequestMethod.OPTIONS, RequestMethod.PATCH, RequestMethod.TRACE })
    @RestController
    public class Controller {

   @Autowired
   Service botService;

   @Autowired
   Environment env;

   @CrossOrigin()
   @RequestMapping(value = "/jwtToken", method = {
                 RequestMethod.POST }, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
   @ResponseStatus(HttpStatus.OK)
   public ResponseEntity<UnifiedService> botConntor(                     
                 @RequestBody UnifiedInput input, HttpServletRequest request) {
          UnifiedBPMService output = botService.processBotRequest(input, request);
          return new ResponseEntity<UnifiedService>(output, HttpStatus.OK);
   }

实际的Angular应用程序中出现的错误是:

跨域资源共享(CORS)策略阻止从源 'http://' 访问 'http:///chatbot/api/jwtToken' 的XMLHttpRequest,因为预检请求的响应未能通过访问控制检查:预检请求不允许重定向。

选项调用返回了以下响应:
    Request URL: http://<domain>/chatbot/api/jwtToken
    Request Method: OPTIONS
    Status Code: 302 Found
    Remote Address: 10.235.222.220:80
    Referrer Policy: no-referrer-when-downgrade

你可以尝试添加@CrossOrigin(origins = { "" }, maxAge = 4800, allowCredentials = "false"),但是origins应该为,并且删除exposed headers。 - Ahmad Qureshi
@AhmadQureshi:建议的更改并没有帮助解决问题。我仍然收到相同的错误。 - KaMaL
你能试着将@CorsOrigin从方法级别中移除吗? - Ahmad Qureshi
@AhmadQureshi:已经移除,但问题仍然存在。 - KaMaL
2个回答

0

你的后端在OPTIONS/preflight请求中重定向(302)而不是发送正确的响应(200)。检查你的后端日志以查看为什么会重定向。可能是Spring安全性拒绝了OPTIONS请求并将其重定向到登录页面。


我遇到了同样的问题,但后端日志根本没有任何数据。 - bhavs
我也遇到了同样的问题。当你使用SSO服务器时,需要在服务器端进行重定向,而不是发送 403 - Amrish
我不确定这是否有所帮助,但在这种情况下,Spring安全日志记录通常非常简洁。我总是采取的第一步是启用调试日志记录。尝试使用-Dlogging.level.org.springframework.security=DEBUG - Christopher Schneider

-1
我遇到了同样的问题。我的问题是它会重定向到登录页面,因为我使用了Spring Security。要确定是否与您的情况相同,可以查看服务器日志。但是您需要启用Spring Security的日志记录。 对于Spring Boot项目,在application.yml文件中:
logging:
  level:
    org:
      springframework:
        security: DEBUG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接