我有一个 ASP.NET Core 7 MVC Web 应用程序,它具有完整的用户身份验证,但也有几个 API 端点。我们需要允许使用客户端证书而不是用户名/密码对这些端点进行身份验证。这可能吗?
我可以看到很多有关在 IIS 中打开客户端证书,甚至关闭某些端点的证书的文档,但我需要相反:我需要为某些端点打开它们,并保留所有其他端点。
过去我使用了可选证书,但浏览器仍然提示用户输入证书,我们不希望这样。
理想情况下,我想要一些简单的东西,只让我在调用特定端点时检查客户端证书,而不是在其他地方?
我问的是不可能的事吗?我是否需要创建一个新的 Web 应用程序并打开客户端证书来为这些端点提供服务?
您可以使用下面的代码通过客户端证书身份验证来保护您的特定 api 调用:
程序.cs:
using Microsoft.AspNetCore.Authentication.Certificate;
using System.Security.Cryptography.X509Certificates;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication("Certificate")
.AddCertificate(options =>
{
options.AllowedCertificateTypes = CertificateTypes.SelfSigned; // Adjust as necessary
options.RevocationMode = X509RevocationMode.NoCheck;
options.Events = new CertificateAuthenticationEvents
{
OnCertificateValidated = context =>
{
// Custom validation logic here, if needed
context.Success();
return Task.CompletedTask;
}
};
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("ClientCertificatePolicy", policy =>
{
policy.AddAuthenticationSchemes("Certificate");
policy.RequireAuthenticatedUser();
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
控制器:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ClientCertApp.Controllers
{
[ApiController]
[Route("api/[controller]")]
[Authorize(Policy = "ClientCertificatePolicy")]
public class SecureApiController : ControllerBase
{
[HttpGet("data")]
public IActionResult GetData()
{
return Ok(new { Message = "This endpoint is protected by client certificate authentication." });
}
}
}