响应CORS飞行前选项请求的401错误

时间:2019-10-09 06:58:43

标签: angular spring spring-boot cors interceptor

我正面临CORS问题,无法在我的代码中找到确切的问题。

我在同一个控制器中有一些API,因为某些API可以正常工作,并且某些API使用OPTIONS方法获得401。而且,如果我尝试通过rest-client访问相同的API,那么一切都很好。即使我们在查询参数中传递访问令牌,然后API仍能正常工作,但在标头中传递令牌时仍会出现问题。

下面是我在Spring Boot中的CORS配置。

public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {

    final HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers",
            "X-Requested-With, Authorization, Origin, Content-Type, Version");
    response.setHeader("Access-Control-Expose-Headers", "X-Requested-With, Authorization, Origin, Content-Type");

    if (!request.getMethod().equals("OPTIONS")) {
        chain.doFilter(req, res);
    } else {
    }
}

下面是拦截器的Angular代码。

    @Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {
  response : any;

  constructor(private route : Router, private localStorage : LocalStorageService) {}

  intercept(req : HttpRequest < any >, next : HttpHandler) : Observable < HttpEvent < any >> {
    if(this.localStorage.get("loggedInUserData") && this.localStorage.get("loggedInUserData").tokenData) {
      req = req.clone({
        setHeaders: {
          Authorization: "Bearer " + this
            .localStorage
            .get("loggedInUserData")
            .tokenData
            .access_token
        }
      })
    }
    return next.handle(req)
  }

谢谢!

0 个答案:

没有答案