Как исправить RevocationStatusUnknown в asp. net core 3.1 с самозаверяющим клиентским сертификатом - PullRequest
2 голосов
/ 24 января 2020
  1. Я пытаюсь реализовать базовое приложение WebAPI asp. net, защищенное сертификатами клиента. Я использовал пример кода из Inte rnet от docs.microsoft и других сайтов. Чтобы проверить, что я построил, я сгенерировал сертификат CA, сертификат сервера и сертификат клиента. Сертификаты как сервера, так и клиента были созданы с использованием этого одного центра сертификации. Я также добавил сертификат CA в хранилище Trusted Root.
    После запуска приложения я получаю сообщение об ошибке 403 Unathorized для каждого вызова этой конечной точки с сертификатом клиента (пробовал из Chrome и Firefox). Наряду с 403 я вижу в консоли сообщение " Проверка сертификата не удалась, тема была ... " и " RevocationStatusUnknown Функция отзыва не смогла проверить отзыв для сертификата. "
  2. Я не понимаю, откуда возникла эта ошибка, поэтому я не могу ее отследить. Я пытался искать в основных источниках asp. net части фразы или отлаживать с использованием символов исходного кода на серверах Microsoft pdb, но я не понимаю, откуда возникла ошибка. Я подозреваю, что это потому, что я использую самоподписанный сертификат, но сообщение об ошибке вводит в заблуждение.
  3. Вот мой код: Program.cs
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Https;
using Microsoft.Extensions.Hosting;

namespace AuthEndpoint
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder
                    .UseStartup<Startup>()
                    .ConfigureKestrel(options =>
                    {
                        options.ConfigureHttpsDefaults(opt =>
                        {
                            opt.ServerCertificate = new X509Certificate2(Path.Combine("c:\\server\\server.pfx"),  "Password");
                            opt.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
                            opt.CheckCertificateRevocation = false;
                            opt.AllowAnyClientCertificate();
                        });
                    });
            });
    }
}

Startup.cs

using System;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Certificate;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AuthEndpoint
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services
                .AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)

                .AddCertificate(options =>
                {
                    options.AllowedCertificateTypes = CertificateTypes.All;
                    options.Events = new CertificateAuthenticationEvents
                    {
                        OnCertificateValidated = context =>
                        {
                            Console.WriteLine(context.ClientCertificate.IssuerName);
                            context.Success();
                            return Task.CompletedTask;
                        },
                        OnAuthenticationFailed = context =>
                        {
                            Console.WriteLine(context.Exception);
                            return Task.CompletedTask;

                        }
                    };
                })
                ;
            services.AddCertificateForwarding(options =>
                {
                    options.CertificateHeader = "X-ARR-ClientCert";
                    options.HeaderConverter = (headerValue) =>
                    {
                        X509Certificate2 clientCertificate = null;
                        if (!string.IsNullOrWhiteSpace(headerValue))
                        {
                            byte[] bytes = Encoding.UTF8.GetBytes(headerValue);
                            clientCertificate = new X509Certificate2(bytes);
                        }
                        return clientCertificate;
                    };
                });
            services.AddAuthorization();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCertificateForwarding();
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

И WeatherForecastController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace AuthEndpoint.Controllers
{
    [ApiController]
    [Route("[controller]")]
    [Authorize]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

Итак, я хотел бы получить ответ о том, как заставить ядро ​​asp. net использовать мой сертификат или если его нет способ использования самоподписанных

1 Ответ

2 голосов
/ 06 февраля 2020

В AddCertificate в настройках необходимо установить следующую строку: options.RevocationMode = X509RevocationMode.NoCheck;

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...