-
Notifications
You must be signed in to change notification settings - Fork 56
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
175 additions
and
188 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
88 changes: 34 additions & 54 deletions
88
examplesUsingCertificateAuthentication/AzureCertAuth/AzureCertAuth/Program.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,54 +1,34 @@ | ||
using Serilog; | ||
using Serilog.Events; | ||
using Serilog.Sinks.SystemConsole.Themes; | ||
|
||
namespace AzureCertAuth; | ||
|
||
public class Program | ||
{ | ||
public static int Main(string[] args) | ||
{ | ||
Log.Logger = new LoggerConfiguration() | ||
.MinimumLevel.Debug() | ||
.MinimumLevel.Override("Microsoft", LogEventLevel.Debug) | ||
.Enrich.FromLogContext() | ||
.CreateLogger(); | ||
|
||
try | ||
{ | ||
Log.Information("Starting web host"); | ||
CreateHostBuilder(args).Build().Run(); | ||
return 0; | ||
} | ||
catch (Exception ex) | ||
{ | ||
Log.Fatal(ex, "Host terminated unexpectedly"); | ||
return 1; | ||
} | ||
finally | ||
{ | ||
Log.CloseAndFlush(); | ||
} | ||
} | ||
|
||
public static IHostBuilder CreateHostBuilder(string[] args) => | ||
Host.CreateDefaultBuilder(args) | ||
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration | ||
.ReadFrom.Configuration(hostingContext.Configuration) | ||
.MinimumLevel.Override("Microsoft", LogEventLevel.Verbose) | ||
.MinimumLevel.Verbose() | ||
.Enrich.FromLogContext() | ||
.WriteTo.File( | ||
//$@"../certauth.txt", | ||
$@"D:\home\LogFiles\Application\{Environment.UserDomainName}.txt", | ||
fileSizeLimitBytes: 1_000_000, | ||
rollOnFileSizeLimit: true, | ||
shared: true, | ||
flushToDiskInterval: TimeSpan.FromSeconds(1)) | ||
.WriteTo.Console(theme: AnsiConsoleTheme.Code) | ||
) | ||
.ConfigureWebHostDefaults(webBuilder => | ||
{ | ||
webBuilder.UseStartup<Startup>(); | ||
}); | ||
} | ||
using AzureCertAuth; | ||
using Serilog; | ||
|
||
Log.Logger = new LoggerConfiguration() | ||
.WriteTo.Console() | ||
.CreateBootstrapLogger(); | ||
|
||
Log.Information("Starting up OpeniddictServer"); | ||
|
||
try | ||
{ | ||
var builder = WebApplication.CreateBuilder(args); | ||
|
||
builder.Host.UseSerilog((context, loggerConfiguration) => loggerConfiguration | ||
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}") | ||
.WriteTo.File("../_logs-DownstreamApiCertAuth.txt") | ||
.Enrich.FromLogContext() | ||
.ReadFrom.Configuration(context.Configuration)); | ||
|
||
var app = builder | ||
.ConfigureServices() | ||
.ConfigurePipeline(); | ||
|
||
app.Run(); | ||
} | ||
catch (Exception ex) when (ex.GetType().Name is not "StopTheHostException" && ex.GetType().Name is not "HostAbortedException") | ||
{ | ||
Log.Fatal(ex, "Unhandled exception"); | ||
} | ||
finally | ||
{ | ||
Log.Information("Shut down complete"); | ||
Log.CloseAndFlush(); | ||
} |
18 changes: 1 addition & 17 deletions
18
...UsingCertificateAuthentication/AzureCertAuth/AzureCertAuth/Properties/launchSettings.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
233 changes: 130 additions & 103 deletions
233
...on/AzureCertAuth/AzureCertAuth/Startup.cs → ...rtAuth/AzureCertAuth/StartupExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,103 +1,130 @@ | ||
using System.Security.Claims; | ||
using System.Security.Cryptography.X509Certificates; | ||
using Microsoft.AspNetCore.Authentication.Certificate; | ||
|
||
namespace AzureCertAuth; | ||
|
||
public class Startup | ||
{ | ||
public Startup(IConfiguration configuration) | ||
{ | ||
Configuration = configuration; | ||
} | ||
|
||
public IConfiguration Configuration { get; } | ||
|
||
public void ConfigureServices(IServiceCollection services) | ||
{ | ||
services.AddSingleton<MyCertificateValidationService>(); | ||
|
||
services.AddCertificateForwarding(options => | ||
{ | ||
options.CertificateHeader = "X-ARR-ClientCert"; | ||
options.HeaderConverter = (headerValue) => | ||
{ | ||
|
||
X509Certificate2? clientCertificate = null; | ||
if (!string.IsNullOrWhiteSpace(headerValue)) | ||
{ | ||
byte[] bytes = Convert.FromBase64String(headerValue); | ||
clientCertificate = new X509Certificate2(bytes); | ||
} | ||
|
||
return clientCertificate; | ||
}; | ||
}); | ||
|
||
services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme) | ||
.AddCertificate(options => // code from ASP.NET Core sample | ||
{ | ||
// https://docs.microsoft.com/en-us/aspnet/core/security/authentication/certauth | ||
options.AllowedCertificateTypes = CertificateTypes.SelfSigned; | ||
|
||
// Default values | ||
//options.AllowedCertificateTypes = CertificateTypes.Chained; | ||
//options.RevocationFlag = X509RevocationFlag.ExcludeRoot; | ||
//options.RevocationMode = X509RevocationMode.Online; | ||
//options.ValidateCertificateUse = true; | ||
//options.ValidateValidityPeriod = true; | ||
|
||
options.Events = new CertificateAuthenticationEvents | ||
{ | ||
OnCertificateValidated = context => | ||
{ | ||
var validationService = | ||
context.HttpContext.RequestServices.GetService<MyCertificateValidationService>(); | ||
|
||
if (validationService!.ValidateCertificate(context.ClientCertificate)) | ||
{ | ||
var claims = new[] | ||
{ | ||
new Claim(ClaimTypes.NameIdentifier, context.ClientCertificate.Subject, ClaimValueTypes.String, context.Options.ClaimsIssuer), | ||
new Claim(ClaimTypes.Name, context.ClientCertificate.Subject, ClaimValueTypes.String, context.Options.ClaimsIssuer) | ||
}; | ||
|
||
context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name)); | ||
context.Success(); | ||
} | ||
else | ||
{ | ||
context.Fail("invalid cert"); | ||
} | ||
|
||
return Task.CompletedTask; | ||
} | ||
}; | ||
}); | ||
|
||
services.AddAuthorization(); | ||
services.AddControllers(); | ||
} | ||
|
||
// 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.UseHttpsRedirection(); | ||
|
||
app.UseRouting(); | ||
|
||
//app.UseCertificateForwarding(); | ||
app.UseAuthentication(); | ||
app.UseAuthorization(); | ||
|
||
app.UseEndpoints(endpoints => | ||
{ | ||
endpoints.MapControllers(); | ||
}); | ||
} | ||
} | ||
using Microsoft.AspNetCore.Authentication.Certificate; | ||
using Microsoft.AspNetCore.Server.Kestrel.Https; | ||
using Microsoft.IdentityModel.JsonWebTokens; | ||
using Microsoft.IdentityModel.Logging; | ||
using Serilog; | ||
using System.Security.Claims; | ||
using System.Security.Cryptography.X509Certificates; | ||
|
||
namespace AzureCertAuth; | ||
|
||
internal static class StartupExtensions | ||
{ | ||
public static WebApplication ConfigureServices(this WebApplicationBuilder builder) | ||
{ | ||
var services = builder.Services; | ||
var configuration = builder.Configuration; | ||
|
||
if(builder.Environment.IsDevelopment()) | ||
{ | ||
builder.WebHost.ConfigureKestrel((context, serverOptions) => | ||
{ | ||
serverOptions.ConfigureHttpsDefaults(listenOptions => | ||
{ | ||
listenOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate; | ||
listenOptions.AllowAnyClientCertificate(); | ||
}); | ||
}); | ||
} | ||
|
||
services.AddSingleton<MyCertificateValidationService>(); | ||
|
||
services.AddCertificateForwarding(options => | ||
{ | ||
options.CertificateHeader = "X-ARR-ClientCert"; | ||
options.HeaderConverter = (headerValue) => | ||
{ | ||
Console.WriteLine("headerValue: " + headerValue); | ||
|
||
X509Certificate2? clientCertificate = null; | ||
if (!string.IsNullOrWhiteSpace(headerValue)) | ||
{ | ||
byte[] bytes = Convert.FromBase64String(headerValue); | ||
clientCertificate = new X509Certificate2(bytes); | ||
} | ||
|
||
return clientCertificate!; | ||
}; | ||
}); | ||
|
||
services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme) | ||
.AddCertificate(options => // code from ASP.NET Core sample | ||
{ | ||
// https://docs.microsoft.com/en-us/aspnet/core/security/authentication/certauth | ||
options.AllowedCertificateTypes = CertificateTypes.All; | ||
|
||
// Default values | ||
//options.AllowedCertificateTypes = CertificateTypes.Chained; | ||
//options.RevocationFlag = X509RevocationFlag.ExcludeRoot; | ||
options.RevocationMode = X509RevocationMode.NoCheck; | ||
options.ValidateCertificateUse = false; | ||
options.ValidateValidityPeriod = false; | ||
|
||
options.Events = new CertificateAuthenticationEvents | ||
{ | ||
OnCertificateValidated = context => | ||
{ | ||
var validationService = | ||
context.HttpContext.RequestServices.GetService<MyCertificateValidationService>(); | ||
|
||
if (validationService!.ValidateCertificate(context.ClientCertificate)) | ||
{ | ||
var claims = new[] | ||
{ | ||
new Claim(ClaimTypes.NameIdentifier, context.ClientCertificate.Subject, ClaimValueTypes.String, context.Options.ClaimsIssuer), | ||
new Claim(ClaimTypes.Name, context.ClientCertificate.Subject, ClaimValueTypes.String, context.Options.ClaimsIssuer) | ||
}; | ||
|
||
context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name)); | ||
context.Success(); | ||
} | ||
else | ||
{ | ||
context.Fail("invalid cert"); | ||
} | ||
|
||
return Task.CompletedTask; | ||
}, | ||
OnAuthenticationFailed = new Func<CertificateAuthenticationFailedContext, Task>(context => | ||
{ | ||
Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message); | ||
return Task.CompletedTask; | ||
}) | ||
}; | ||
}); | ||
|
||
services.AddAuthorization(); | ||
services.AddControllers(); | ||
|
||
return builder.Build(); | ||
} | ||
|
||
public static WebApplication ConfigurePipeline(this WebApplication app) | ||
{ | ||
IdentityModelEventSource.ShowPII = true; | ||
JsonWebTokenHandler.DefaultInboundClaimTypeMap.Clear(); | ||
|
||
app.UseSerilogRequestLogging(); | ||
|
||
if (app.Environment.IsDevelopment()) | ||
{ | ||
app.UseDeveloperExceptionPage(); | ||
} | ||
|
||
app.UseHttpsRedirection(); | ||
|
||
app.UseRouting(); | ||
|
||
if (app.Environment.IsDevelopment()) | ||
{ | ||
app.UseCertificateForwarding(); | ||
} | ||
|
||
app.UseAuthentication(); | ||
app.UseAuthorization(); | ||
|
||
app.MapControllers(); | ||
|
||
return app; | ||
} | ||
} |
Binary file removed
BIN
-1.07 KB
examplesUsingCertificateAuthentication/AzureCertAuth/AzureCertAuth/server.pfx
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters