angular - .NET Core 3.1 + Angular 上的 PreflightMissingAllowOriginHeader CORS 错误
问题描述
我正在.NET Core 3.1 + Angular 上开发一个应用程序,直到最近,当我尝试在后端实现协商身份验证配置时,一切都运行良好。无论如何,即使在还原所有身份验证配置后问题仍然存在,因此它可能不相关。
我收到 CORS 错误,描述 PreflightMissingAllowOriginHeader 后跟 401 错误。
下面你可以看到我的代码。出于沮丧,当我尝试调试此问题时,我什至允许所有来源、标头和方法。
启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials(); });
});
// Tried both ^ and v
/* services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder => { builder.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod().AllowCredentials(); });
});*/
.
.
.
.
services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
.
.
.
.
.
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
/* app.UseHttpsRedirection();*/
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors(MyAllowSpecificOrigins); // <--- Tried both with and without RequireCors
});
}
Angular WebReqService
readonly ROOT_URL: string;
readonly httpHeaders: HttpHeaders = new HttpHeaders({'Content-Type': 'application/json'});
readonly httpOptions = {
headers: this.httpHeaders,
withCredentials: true
};
constructor(private http: HttpClient) {
this.ROOT_URL = 'http://localhost:5000';
}
get(uri: string): Observable<any> {
return this.http.get<any[]>(`${this.ROOT_URL}/${uri}`, this.httpOptions);
}
最奇怪的是,如果我尝试通过在浏览器中调用请求或在 Insomnia 中使用 NTLM 授权直接访问 API,一切正常。只有当我尝试从 Angular FE 访问 API 时,才会收到错误消息。
任何想法可能是什么原因以及如何解决它? 另外,我认为这不是由于没有被授权使用该应用程序引起的,因为正如我所说它在 Angular 之外工作,而且如果用户没有被授权,它被配置为返回 403 而不是 401。
解决方案
您可以尝试设置 Angular 代理。
1 - 在您的 Angular 应用程序的根目录下创建一个文件 proxy.conf.js,内容如下:
const PROXY_CONFIG = [
{
context: ["/api"],
target: "http://localhost:5000",
secure: false,
logLevel: "error",
changeOrigin: true,
}
];
module.exports = PROXY_CONFIG;
2 - 在项目中的 angular.json -> yourprojectname -> 架构师 -> 服务 -> 配置 -> 开发,添加“proxyConfig”:“proxy.conf.js”
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "client:build:production"
},
"development": {
"browserTarget": "client:build:development",
"proxyConfig": "proxy.conf.js"
}
},
3 - 在你的 Angular WebReqService 中,设置 this.ROOT_URL = 'http://localhost:4200';
推荐阅读
- c++11 - windows makefile 中的 cl 选项是否会接受 -std=c++11 标志?
- java - 来自无限 Java 流的通量端点
- configuration - 通过 appsettings.json 为 Application Insights 配置 Serilog
- java - 软件内的数据库集成
- java - 如何在异步任务的 android 应用程序中添加 Internet 连接问题对话框
- javascript - javascript 添加新表单
- xml - 我可以使用哪个支持 IBM Datapower 扩展的 Java XSLT 处理器?
- neo4j - 如何使用 WITH 子句正确携带值
- audio - 是否可以使用 Office 通用 API 从加载项插入视频?
- java - Appium:如何使用 java 中的自动化测试用例检查设备名称