【问题标题】:Angular frontend not sending authorization cookie when requesting across origins (even with withCredentials)跨源请求时,Angular 前端不发送授权 cookie(即使使用 withCredentials)
【发布时间】:2022-11-26 03:56:22
【问题描述】:

好吧,我一整天都被这个问题困住了。

我在localhost:4200 上本地托管了一个 Angular 前端,在localhost:8080 上有一个 Spring Boot 后端。

我可以成功地从 Angular 应用程序中访问 localhost:8080/api/login 端点,并返回一个 Set-Cookie 标头。这是点击/login的回复

<1234565 class="剧透">

问题是在进行后续调用时,例如localhost:8080/api/test,我收到 401。似乎是因为 Cookie 没有随请求一起发送。这是请求/响应的样子

<1234565 class="剧透">

>!

我也可以给出的一些重要发现/考虑是

  1. 当通过 Postman 访问 /login 端点然后访问 /test 端点时,一切正常。
  2. 如果我通过配置了 Webpack 代理的 Angular 项目访问 /login 端点,然后访问 /test 端点,它会完美运行(即向 localhost:4200/api/login 发出请求,然后告诉 Webpack 在内部转发那到本地主机:8080)。因此,我认为这个问题在某种程度上与 CORS 有关。因为似乎当浏览器认为正在向 localhost:4200 (即同一域)发出请求时,它会按预期发送 cookie

【问题讨论】:

    标签: angular spring authentication


    【解决方案1】:

    你试一下

    @Component
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public class SimpleCORSFilter implements Filter {
    
        
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            Filter.super.init(filterConfig);
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) resp;
            HttpServletRequest request = (HttpServletRequest) req;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEAD, OPTIONS");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");
    
            String method = request.getMethod();
    
            if ("OPTIONS".equalsIgnoreCase(method)) {
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                chain.doFilter(req, resp);
            }
        }
    
        @Override
        public void destroy() {
            Filter.super.destroy();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-16
      • 2020-05-21
      • 2018-10-09
      • 2019-02-11
      • 2020-06-30
      • 2015-05-11
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      相关资源
      最近更新 更多