/// <summary>
        /// Adds an certificate authentication MVC filter to the given <paramref name="filters"/> that authenticates the incoming HTTP request.
        /// </summary>
        /// <param name="filters">The current MVC filters of the application.</param>
        /// <param name="configureOptions">
        ///     The optional function to configure the set of additional consumer-configurable options to change the behavior of the certificate authentication.
        /// </param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="filters"/> is <c>null</c>.</exception>
        public static FilterCollection AddCertificateAuthentication(
            this FilterCollection filters,
            Action <CertificateAuthenticationOptions> configureOptions)
        {
            Guard.NotNull(filters, nameof(filters), "Requires a set of MVC filters to add the certificate authentication MVC filter");

            var options = new CertificateAuthenticationOptions();

            configureOptions?.Invoke(options);

            filters.Add(new CertificateAuthenticationFilter(options));
            return(filters);
        }
 private static void configureCertificateOptions(CertificateAuthenticationOptions options)
 {
     // Not recommended in production. The example is using a self-signed test certificate.
     options.AllowedCertificateTypes = CertificateTypes.SelfSigned;
     options.RevocationMode          = X509RevocationMode.NoCheck;
     //options.Events                  = new CertificateAuthenticationEvents()
     //{
     //  OnCertificateValidated = ctx =>
     //  {
     //    // Write additional validation.
     //    ctx.Success();
     //    return Task.CompletedTask;
     //  }
     //};
 }
        private static async Task <IHost> CreateHost(
            CertificateAuthenticationOptions configureOptions,
            X509Certificate2 clientCertificate = null,
            Func <HttpContext, bool> handler   = null,
            Uri baseAddress             = null,
            bool wireUpHeaderMiddleware = false,
            string headerName           = "",
            bool useCache = false)
        {
            var host = new HostBuilder()
                       .ConfigureWebHost(builder =>
                                         builder.UseTestServer()
                                         .Configure(app =>
            {
                app.Use((context, next) =>
                {
                    if (clientCertificate != null)
                    {
                        context.Connection.ClientCertificate = clientCertificate;
                    }
                    return(next());
                });


                if (wireUpHeaderMiddleware)
                {
                    app.UseCertificateForwarding();
                }

                app.UseAuthentication();

                app.Use(async(context, next) =>
                {
                    var request  = context.Request;
                    var response = context.Response;

                    var authenticationResult = await context.AuthenticateAsync();

                    if (authenticationResult.Succeeded)
                    {
                        response.StatusCode  = (int)HttpStatusCode.OK;
                        response.ContentType = "text/xml";

                        await response.WriteAsync("<claims>");
                        foreach (Claim claim in context.User.Claims)
                        {
                            await response.WriteAsync($"<claim Type=\"{claim.Type}\" Issuer=\"{claim.Issuer}\">{claim.Value}</claim>");
                        }
                        await response.WriteAsync("</claims>");
                    }
                    else
                    {
                        await context.ChallengeAsync();
                    }
                });
            })
                                         .ConfigureServices(services =>
            {
                AuthenticationBuilder authBuilder;
                if (configureOptions != null)
                {
                    authBuilder = services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme).AddCertificate(options =>
                    {
                        options.CustomTrustStore         = configureOptions.CustomTrustStore;
                        options.ChainTrustValidationMode = configureOptions.ChainTrustValidationMode;
                        options.AllowedCertificateTypes  = configureOptions.AllowedCertificateTypes;
                        options.Events = configureOptions.Events;
                        options.ValidateCertificateUse      = configureOptions.ValidateCertificateUse;
                        options.RevocationFlag              = configureOptions.RevocationFlag;
                        options.RevocationMode              = configureOptions.RevocationMode;
                        options.ValidateValidityPeriod      = configureOptions.ValidateValidityPeriod;
                        options.AdditionalChainCertificates = configureOptions.AdditionalChainCertificates;
                    });
                }
                else
                {
                    authBuilder = services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme).AddCertificate();
                }
                if (useCache)
                {
                    authBuilder.AddCertificateCache();
                }

                if (wireUpHeaderMiddleware && !string.IsNullOrEmpty(headerName))
                {
                    services.AddCertificateForwarding(options =>
                    {
                        options.CertificateHeader = headerName;
                    });
                }
            }))
                       .Build();

            await host.StartAsync();


            var server = host.GetTestServer();

            server.BaseAddress = baseAddress;
            return(host);
        }
Exemple #4
0
        private static TestServer CreateServer(
            CertificateAuthenticationOptions configureOptions,
            X509Certificate2 clientCertificate = null,
            Func <HttpContext, bool> handler   = null,
            Uri baseAddress             = null,
            bool wireUpHeaderMiddleware = false,
            string headerName           = "")
        {
            var builder = new WebHostBuilder()
                          .Configure(app =>
            {
                app.Use((context, next) =>
                {
                    if (clientCertificate != null)
                    {
                        context.Connection.ClientCertificate = clientCertificate;
                    }
                    return(next());
                });


                if (wireUpHeaderMiddleware)
                {
                    app.UseCertificateHeaderForwarding();
                }

                app.UseAuthentication();

                app.Use(async(context, next) =>
                {
                    var request  = context.Request;
                    var response = context.Response;

                    var authenticationResult = await context.AuthenticateAsync();

                    if (authenticationResult.Succeeded)
                    {
                        response.StatusCode = (int)HttpStatusCode.OK;
                    }
                    else
                    {
                        await context.ChallengeAsync();
                    }
                });
            })
                          .ConfigureServices(services =>
            {
                if (configureOptions != null)
                {
                    services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme).AddCertificate(options =>
                    {
                        options.AllowedCertificateTypes = configureOptions.AllowedCertificateTypes;
                        options.Events = configureOptions.Events;
                        options.ValidateCertificateUse = configureOptions.ValidateCertificateUse;
                        options.RevocationFlag         = options.RevocationFlag;
                        options.RevocationMode         = options.RevocationMode;
                        options.ValidateValidityPeriod = configureOptions.ValidateValidityPeriod;
                    });
                }
                else
                {
                    services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme).AddCertificate();
                }

                if (wireUpHeaderMiddleware && !string.IsNullOrEmpty(headerName))
                {
                    services.AddCertificateHeaderForwarding(options =>
                    {
                        options.CertificateHeader = headerName;
                    });
                }
            });

            var server = new TestServer(builder)
            {
                BaseAddress = baseAddress
            };

            return(server);
        }