Basic Auth保护后如何使用Angular?

How to use Angular behind Basic Auth protection?

我们有一个在 Apache 和 nginx 上运行的 Angular 8 应用程序。我们使用 .htaccess.htpasswd.

的基本身份验证来保护此应用程序

遗憾的是,由于对服务器的请求被基本身份验证阻止并且 Angular 无法加载这些文件,因此应用程序将无法加载:

Blocked http://root/polyfills-es2015.js from asking for credentials because it is a cross-origin request.
Blocked http://root/runtime-es2015.js from asking for credentials because it is a cross-origin request.
Failed to load resource: the server responded with a status of 401 (Authorization Required) (runtime-es2015.js, line 0)
Blocked http://root/styles-es2015.js from asking for credentials because it is a cross-origin request.
Failed to load resource: the server responded with a status of 401 (Authorization Required) (styles-es2015.js, line 0)
Blocked http://root/vendor-es2015.js from asking for credentials because it is a cross-origin request. Blocked http://root/main-es2015.js from asking for credentials because it is a cross-origin request.
Failed to load resource: the server responded with a status of 401 (Authorization Required) (vendor-es2015.js, line 0)
Failed to load resource: the server responded with a status of 401 (Authorization Required) (main-es2015.js, line 0)
Failed to load resource: the server responded with a status of 401 (Authorization Required) (polyfills-es2015.js, line 0)

如果我们删除对 .htpasswd 的引用,应用程序将按预期运行。

我尝试使用自定义 HTTP 拦截器:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  const cloned = req.clone({
    headers: req.headers.set('Authorization', 'Basic ' + btoa('user:password'))
  });

  return next.handle(cloned);
}

但是,这似乎没有用于 Angular 的内部加载机制。

我们怎样才能让它发挥作用?

问题不在您的 Angular 代码中,而是在后端配置中。

您需要在后端启用 CORS(跨源请求)。现在,您的后端不允许请求通过以防止任何网站发送请求(防止跨站点脚本攻击)。

因此,您应该查看 nginxApache 如何启用 CORS。这个网站似乎给出了一个简短而好的介绍:https://enable-cors.org/server_apache.html。但是要注意限制允许的来源,这样你就不会为潜在的攻击者敞开大门。