[Security] Move to GenericHost (#24282)

This commit is contained in:
Kahbazi 2020-07-28 00:39:15 +04:30 committed by GitHub
parent 780d527f0b
commit 6097145096
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 335 additions and 211 deletions

View File

@ -1,26 +1,30 @@
using Microsoft.AspNetCore;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Https;
using Microsoft.Extensions.Hosting;
namespace Certificate.Sample
{
public class Program
{
public static void Main(string[] args)
public static Task Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args)
=> WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureKestrel(options =>
{
options.ConfigureHttpsDefaults(opt =>
var host = Host.CreateDefaultBuilder(args)
.ConfigureWebHost(webHostBuilder =>
{
opt.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
});
})
.Build();
webHostBuilder
.UseStartup<Startup>()
.ConfigureKestrel(options =>
{
options.ConfigureHttpsDefaults(opt =>
{
opt.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
});
});
})
.Build();
return host.RunAsync();
}
}
}

View File

@ -1,26 +1,32 @@
using System.IO;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace CookieSample
{
public static class Program
{
public static void Main(string[] args)
public static Task Main(string[] args)
{
var host = new WebHostBuilder()
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
})
.ConfigureLogging(factory =>
{
factory.AddConsole();
factory.AddFilter("Console", level => level >= LogLevel.Information);
})
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
return host.RunAsync();
}
}
}

View File

@ -1,26 +1,32 @@
using System.IO;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace CookieSessionSample
{
public static class Program
{
public static void Main(string[] args)
public static Task Main(string[] args)
{
var host = new WebHostBuilder()
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
})
.ConfigureLogging(factory =>
{
factory.AddConsole();
factory.AddFilter("Console", level => level >= LogLevel.Information);
})
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
return host.RunAsync();
}
}
}

View File

@ -1,4 +1,4 @@
using Microsoft.AspNetCore;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
@ -6,13 +6,17 @@ namespace JwtBearerSample
{
public static class Program
{
public static void Main(string[] args)
public static Task Main(string[] args)
{
var host = WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
var host = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webHostBuilder =>
{
webHostBuilder
.UseStartup<Startup>();
})
.Build();
host.Run();
return host.RunAsync();
}
}
}

View File

@ -1,17 +1,22 @@
using Microsoft.AspNetCore;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace OpenIdConnect.AzureAdSample
{
public static class Program
{
public static void Main(string[] args)
public static Task Main(string[] args)
{
var host = WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
var host = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webHostBuilder =>
{
webHostBuilder
.UseStartup<Startup>();
})
.Build();
host.Run();
return host.RunAsync();
}
}
}

View File

@ -1,18 +1,23 @@
using Microsoft.AspNetCore;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace OpenIdConnectSample
{
public static class Program
{
public static void Main(string[] args)
public static Task Main(string[] args)
{
var host = WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
var host = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webHostBuilder =>
{
webHostBuilder
.UseStartup<Startup>();
})
.Build();
host.Run();
return host.RunAsync();
}
}
}

View File

@ -1,24 +1,36 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WsFedSample
{
public class Program
{
public static void Main(string[] args)
public static Task Main(string[] args)
{
var host = new WebHostBuilder()
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options =>
{
options.Listen(IPAddress.Loopback, 44307, listenOptions =>
{
// Configure SSL
var serverCertificate = LoadCertificate();
listenOptions.UseHttps(serverCertificate);
});
})
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
})
.ConfigureLogging(factory =>
{
factory.AddConsole();
@ -26,21 +38,9 @@ namespace WsFedSample
factory.AddFilter("Console", level => level >= LogLevel.Information);
factory.AddFilter("Debug", level => level >= LogLevel.Information);
})
.UseKestrel(options =>
{
options.Listen(IPAddress.Loopback, 44307, listenOptions =>
{
// Configure SSL
var serverCertificate = LoadCertificate();
listenOptions.UseHttps(serverCertificate);
});
})
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
return host.RunAsync();
}
private static X509Certificate2 LoadCertificate()

View File

@ -437,7 +437,22 @@ namespace Microsoft.AspNetCore.Authentication.Test.OpenIdConnect
[Fact]
public async Task MetadataAddressIsGeneratedFromAuthorityWhenMissing()
{
var builder = new WebHostBuilder()
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.Configure(app =>
{
app.UseAuthentication();
app.Run(async context =>
{
var resolver = context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
var handler = await resolver.GetHandlerAsync(context, OpenIdConnectDefaults.AuthenticationScheme) as OpenIdConnectHandler;
Assert.Equal($"{TestServerBuilder.DefaultAuthority}/.well-known/openid-configuration", handler.Options.MetadataAddress);
});
})
.UseTestServer();
})
.ConfigureServices(services =>
{
services.AddAuthentication()
@ -449,17 +464,11 @@ namespace Microsoft.AspNetCore.Authentication.Test.OpenIdConnect
o.SignInScheme = Guid.NewGuid().ToString();
});
})
.Configure(app =>
{
app.UseAuthentication();
app.Run(async context =>
{
var resolver = context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
var handler = await resolver.GetHandlerAsync(context, OpenIdConnectDefaults.AuthenticationScheme) as OpenIdConnectHandler;
Assert.Equal($"{TestServerBuilder.DefaultAuthority}/.well-known/openid-configuration", handler.Options.MetadataAddress);
});
});
var server = new TestServer(builder);
.Build();
var server = host.GetTestServer();
await host.StartAsync();
var transaction = await server.SendAsync(@"https://example.com");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
}

View File

@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Xunit;
namespace Microsoft.AspNetCore.Authentication
@ -17,7 +18,7 @@ namespace Microsoft.AspNetCore.Authentication
[Fact]
public async Task CanDispatch()
{
var server = CreateServer(services =>
using var server = await CreateServer(services =>
{
services.AddLogging().AddAuthentication(o =>
{
@ -333,7 +334,7 @@ namespace Microsoft.AspNetCore.Authentication
[Fact]
public async Task CanDynamicTargetBasedOnQueryString()
{
var server = CreateServer(services =>
using var server = await CreateServer(services =>
{
services.AddAuthentication(o =>
{
@ -455,33 +456,44 @@ namespace Microsoft.AspNetCore.Authentication
}
}
private static TestServer CreateServer(Action<IServiceCollection> configure = null, string defaultScheme = null)
private static async Task<TestServer> CreateServer(Action<IServiceCollection> configure = null, string defaultScheme = null)
{
var builder = new WebHostBuilder()
.Configure(app =>
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
app.UseAuthentication();
app.Use(async (context, next) =>
{
var req = context.Request;
var res = context.Response;
if (req.Path.StartsWithSegments(new PathString("/auth"), out var remainder))
webHostBuilder
.Configure(app =>
{
var name = (remainder.Value.Length > 0) ? remainder.Value.Substring(1) : null;
var result = await context.AuthenticateAsync(name);
await res.DescribeAsync(result?.Ticket?.Principal);
}
else
{
await next();
}
});
app.UseAuthentication();
app.Use(async (context, next) =>
{
var req = context.Request;
var res = context.Response;
if (req.Path.StartsWithSegments(new PathString("/auth"), out var remainder))
{
var name = (remainder.Value.Length > 0) ? remainder.Value.Substring(1) : null;
var result = await context.AuthenticateAsync(name);
await res.DescribeAsync(result?.Ticket?.Principal);
}
else
{
await next();
}
});
})
.UseTestServer();
})
.ConfigureServices(services =>
{
configure?.Invoke(services);
});
return new TestServer(builder);
})
.Build();
var server = host.GetTestServer();
await host.StartAsync();
return server;
}
}
}

View File

@ -1,26 +1,32 @@
using System.IO;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace CookiePolicySample
{
public static class Program
{
public static void Main(string[] args)
public static Task Main(string[] args)
{
var host = new WebHostBuilder()
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
})
.ConfigureLogging(factory =>
{
factory.AddConsole();
factory.AddFilter("Microsoft", LogLevel.Trace);
})
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
return host.RunAsync();
}
}
}

View File

@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Net.Http.Headers;
using Xunit;
@ -641,20 +642,30 @@ namespace Microsoft.AspNetCore.CookiePolicy.Test
Assert.NotNull(manualCookie.Expires); // Expires may not exactly match to the second.
}
private Task<HttpContext> RunTestAsync(Action<CookiePolicyOptions> configureOptions, Action<HttpContext> configureRequest, RequestDelegate handleRequest)
private async Task<HttpContext> RunTestAsync(Action<CookiePolicyOptions> configureOptions, Action<HttpContext> configureRequest, RequestDelegate handleRequest)
{
var builder = new WebHostBuilder()
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.Configure(app =>
{
app.UseCookiePolicy();
app.Run(handleRequest);
})
.UseTestServer();
})
.ConfigureServices(services =>
{
services.Configure(configureOptions);
})
.Configure(app =>
{
app.UseCookiePolicy();
app.Run(handleRequest);
});
var server = new TestServer(builder);
return server.SendAsync(configureRequest);
.Build();
var server = host.GetTestServer();
await host.StartAsync();
return await server.SendAsync(configureRequest);
}
}
}

View File

@ -13,6 +13,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Net.Http.Headers;
using Xunit;
@ -244,23 +245,32 @@ namespace Microsoft.AspNetCore.CookiePolicy.Test
[Fact]
public async Task CookiePolicyCanHijackAppend()
{
var builder = new WebHostBuilder()
.Configure(app =>
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
app.UseCookiePolicy(new CookiePolicyOptions
{
OnAppendCookie = ctx => ctx.CookieName = ctx.CookieValue = "Hao"
});
app.Run(context =>
{
context.Response.Cookies.Append("A", "A");
context.Response.Cookies.Append("B", "B", new CookieOptions { Secure = false });
context.Response.Cookies.Append("C", "C", new CookieOptions() { SameSite = Http.SameSiteMode.Strict });
context.Response.Cookies.Append("D", "D", new CookieOptions { Secure = true });
return Task.FromResult(0);
});
});
var server = new TestServer(builder);
webHostBuilder
.Configure(app =>
{
app.UseCookiePolicy(new CookiePolicyOptions
{
OnAppendCookie = ctx => ctx.CookieName = ctx.CookieValue = "Hao"
});
app.Run(context =>
{
context.Response.Cookies.Append("A", "A");
context.Response.Cookies.Append("B", "B", new CookieOptions { Secure = false });
context.Response.Cookies.Append("C", "C", new CookieOptions() { SameSite = Http.SameSiteMode.Strict });
context.Response.Cookies.Append("D", "D", new CookieOptions { Secure = true });
return Task.FromResult(0);
});
})
.UseTestServer();
})
.Build();
var server = host.GetTestServer();
await host.StartAsync();
var transaction = await server.SendAsync("http://example.com/login");
@ -274,23 +284,32 @@ namespace Microsoft.AspNetCore.CookiePolicy.Test
[Fact]
public async Task CookiePolicyCanHijackDelete()
{
var builder = new WebHostBuilder()
.Configure(app =>
{
app.UseCookiePolicy(new CookiePolicyOptions
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
OnDeleteCookie = ctx => ctx.CookieName = "A"
});
app.Run(context =>
{
context.Response.Cookies.Delete("A");
context.Response.Cookies.Delete("B", new CookieOptions { Secure = false });
context.Response.Cookies.Delete("C", new CookieOptions());
context.Response.Cookies.Delete("D", new CookieOptions { Secure = true });
return Task.FromResult(0);
});
});
var server = new TestServer(builder);
webHostBuilder
.Configure(app =>
{
app.UseCookiePolicy(new CookiePolicyOptions
{
OnDeleteCookie = ctx => ctx.CookieName = "A"
});
app.Run(context =>
{
context.Response.Cookies.Delete("A");
context.Response.Cookies.Delete("B", new CookieOptions { Secure = false });
context.Response.Cookies.Delete("C", new CookieOptions());
context.Response.Cookies.Delete("D", new CookieOptions { Secure = true });
return Task.FromResult(0);
});
})
.UseTestServer();
})
.Build();
var server = host.GetTestServer();
await host.StartAsync();
var transaction = await server.SendAsync("http://example.com/login");
@ -302,28 +321,37 @@ namespace Microsoft.AspNetCore.CookiePolicy.Test
[Fact]
public async Task CookiePolicyCallsCookieFeature()
{
var builder = new WebHostBuilder()
.Configure(app =>
{
app.Use(next => context =>
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
context.Features.Set<IResponseCookiesFeature>(new TestCookieFeature());
return next(context);
});
app.UseCookiePolicy(new CookiePolicyOptions
{
OnDeleteCookie = ctx => ctx.CookieName = "A"
});
app.Run(context =>
{
Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Delete("A"));
Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Delete("A", new CookieOptions()));
Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Append("A", "A"));
Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Append("A", "A", new CookieOptions()));
return context.Response.WriteAsync("Done");
});
});
var server = new TestServer(builder);
webHostBuilder
.Configure(app =>
{
app.Use(next => context =>
{
context.Features.Set<IResponseCookiesFeature>(new TestCookieFeature());
return next(context);
});
app.UseCookiePolicy(new CookiePolicyOptions
{
OnDeleteCookie = ctx => ctx.CookieName = "A"
});
app.Run(context =>
{
Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Delete("A"));
Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Delete("A", new CookieOptions()));
Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Append("A", "A"));
Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Append("A", "A", new CookieOptions()));
return context.Response.WriteAsync("Done");
});
})
.UseTestServer();
})
.Build();
var server = host.GetTestServer();
await host.StartAsync();
var transaction = await server.SendAsync("http://example.com/login");
Assert.Equal("Done", transaction.ResponseText);
@ -332,7 +360,26 @@ namespace Microsoft.AspNetCore.CookiePolicy.Test
[Fact]
public async Task CookiePolicyAppliesToCookieAuth()
{
var builder = new WebHostBuilder()
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.Configure(app =>
{
app.UseCookiePolicy(new CookiePolicyOptions
{
HttpOnly = HttpOnlyPolicy.Always,
Secure = CookieSecurePolicy.Always,
});
app.UseAuthentication();
app.Run(context =>
{
return context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("TestUser", "Cookies"))));
});
})
.UseTestServer();
})
.ConfigureServices(services =>
{
services.AddAuthentication().AddCookie(o =>
@ -342,21 +389,11 @@ namespace Microsoft.AspNetCore.CookiePolicy.Test
o.Cookie.SecurePolicy = CookieSecurePolicy.None;
});
})
.Configure(app =>
{
app.UseCookiePolicy(new CookiePolicyOptions
{
HttpOnly = HttpOnlyPolicy.Always,
Secure = CookieSecurePolicy.Always,
});
app.UseAuthentication();
app.Run(context =>
{
return context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("TestUser", "Cookies"))));
});
});
var server = new TestServer(builder);
.Build();
var server = host.GetTestServer();
await host.StartAsync();
var transaction = await server.SendAsync("http://example.com/login");
@ -372,7 +409,26 @@ namespace Microsoft.AspNetCore.CookiePolicy.Test
[Fact]
public async Task CookiePolicyAppliesToCookieAuthChunks()
{
var builder = new WebHostBuilder()
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.Configure(app =>
{
app.UseCookiePolicy(new CookiePolicyOptions
{
HttpOnly = HttpOnlyPolicy.Always,
Secure = CookieSecurePolicy.Always,
});
app.UseAuthentication();
app.Run(context =>
{
return context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity(new string('c', 1024 * 5), "Cookies"))));
});
})
.UseTestServer();
})
.ConfigureServices(services =>
{
services.AddAuthentication().AddCookie(o =>
@ -382,21 +438,11 @@ namespace Microsoft.AspNetCore.CookiePolicy.Test
o.Cookie.SecurePolicy = CookieSecurePolicy.None;
});
})
.Configure(app =>
{
app.UseCookiePolicy(new CookiePolicyOptions
{
HttpOnly = HttpOnlyPolicy.Always,
Secure = CookieSecurePolicy.Always,
});
app.UseAuthentication();
app.Run(context =>
{
return context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity(new string('c', 1024 * 5), "Cookies"))));
});
});
var server = new TestServer(builder);
.Build();
var server = host.GetTestServer();
await host.StartAsync();
var transaction = await server.SendAsync("http://example.com/login");
@ -475,16 +521,26 @@ namespace Microsoft.AspNetCore.CookiePolicy.Test
RequestDelegate configureSetup,
params RequestTest[] tests)
{
var builder = new WebHostBuilder()
.Configure(app =>
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
app.Map(path, map =>
{
map.UseCookiePolicy(cookiePolicy);
map.Run(configureSetup);
});
});
var server = new TestServer(builder);
webHostBuilder
.Configure(app =>
{
app.Map(path, map =>
{
map.UseCookiePolicy(cookiePolicy);
map.Run(configureSetup);
});
})
.UseTestServer();
})
.Build();
var server = host.GetTestServer();
await host.StartAsync();
foreach (var test in tests)
{
await test.Execute(server);