net::ERR_CERT_AUTHORITY_INVALID 在 ASP.NET 核心

net::ERR_CERT_AUTHORITY_INVALID in ASP.NET Core

当我尝试从 SPA 请求我的 Web API 时,我在 ASP.NET Core 中收到 net::ERR_CERT_AUTHORITY_INVALID 错误。

解决该问题的第一个解决方案是从浏览器 Advanced - Proceed to localhost (unsafe) 获取我的 ASP.NET 核心地址,然后来自我的 SPA 的请求将起作用。但是每次我开始处理我的项目时,我都必须重复这个过程。

我找到的另一个解决方案是 this。简而言之,解决方案是 运行 命令:dotnet dev-certs https --trust。我在 Windows,所以根据链接文章 On Windows it'll get added to the certificate store

但是在我 运行 命令之后,我仍然收到请求的 net::ERR_CERT_AUTHORITY_INVALID 问题。我该怎么办?

在您的应用程序中,通过 NuGet 包添加对 Microsoft.AspNetCore.Authentication.Certificate 的引用。然后在Startup.ConfigureServices方法中这样写:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(
        CertificateAuthenticationDefaults.AuthenticationScheme)
        .AddCertificate();

    // All other service configuration
}


同时添加app.UseAuthentication();在 Startup.Configure 方法中。否则,HttpContext.User 将不会设置为 ClaimsPrincipal

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   app.UseAuthentication();

    // All other app configuration
}

来源:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/certauth?view=aspnetcore-3.1

我按照这些步骤操作,但并没有阻止 Chrome 中出现的“不安全”消息。然后我尝试评论以下行 //app.UseHttpsRedirection();在 startup.cs 的 Configure() 方法中解决了问题。

运行 命令 dotnet dev-certs https --trust 将在您的设备中创建一个 self-signed 证书。此证书将颁发给 localhost 域。在我的例子中,在 运行 之后,证书被创建,但它没有被添加到“受信任的根证书颁发机构”。

要添加证书,您需要打开certmgr.msc (win+r and 运行 certmgr.msc),然后转到“个人”证书并导出颁发给 localhost 且具有正确到期时间的 .cer 证书。

如果在那里找不到证书,您可以转到浏览器并单击不安全连接图标,然后打开无效证书并转到“详细信息”选项卡并单击“复制到文件...”,这也应该创建一个 .cer 证书。

接下来,转到“受信任的根证书颁发机构”并在那里导入证书。完成后,证书将在您的本地计算机上有效。您可能需要重新启动浏览器和服务。