Reacting to new Hosting API

This commit is contained in:
John Luo 2015-12-18 10:49:37 -08:00
parent 965a86e404
commit a041807023
29 changed files with 590 additions and 479 deletions

View File

@ -22,11 +22,6 @@
"environmentVariables": { "environmentVariables": {
"Hosting:Environment": "Development" "Hosting:Environment": "Development"
} }
},
"kestrel": {
"commandName": "kestrel",
"launchBrowser": true,
"launchUrl": "http://localhost:5004"
} }
} }
} }

View File

@ -2,6 +2,7 @@ using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNet.Authentication.Cookies; using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -40,5 +41,15 @@ namespace CookieSample
await context.Response.WriteAsync("Hello old timer"); await context.Response.WriteAsync("Hello old timer");
}); });
} }
public static void Main(string[] args)
{
var application = new WebApplicationBuilder()
.UseConfiguration(WebApplicationConfiguration.GetDefault(args))
.UseStartup<Startup>()
.Build();
application.Run();
}
} }
} }

View File

@ -0,0 +1,3 @@
{
"server": "Microsoft.AspNet.Server.Kestrel"
}

View File

@ -4,12 +4,13 @@
"Microsoft.AspNet.DataProtection": "1.0.0-*", "Microsoft.AspNet.DataProtection": "1.0.0-*",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-*", "Microsoft.AspNet.IISPlatformHandler": "1.0.0-*",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-*", "Microsoft.AspNet.Server.Kestrel": "1.0.0-*",
"Microsoft.AspNet.Server.WebListener": "1.0.0-*",
"Microsoft.Extensions.Logging.Console": "1.0.0-*" "Microsoft.Extensions.Logging.Console": "1.0.0-*"
}, },
"compilationOptions": {
"emitEntryPoint": true
},
"commands": { "commands": {
"web": "Microsoft.AspNet.Server.Kestrel", "web": "CookieSample"
"weblistener": "Microsoft.AspNet.Server.WebListener"
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "dnx451": { },

View File

@ -22,11 +22,6 @@
"environmentVariables": { "environmentVariables": {
"Hosting:Environment": "Development" "Hosting:Environment": "Development"
} }
},
"kestrel": {
"commandName": "kestrel",
"launchBrowser": true,
"launchUrl": "http://localhost:5004"
} }
} }
} }

View File

@ -3,6 +3,7 @@ using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Authentication.Cookies; using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -50,5 +51,15 @@ namespace CookieSessionSample
await context.Response.WriteAsync("Hello old timer"); await context.Response.WriteAsync("Hello old timer");
}); });
} }
public static void Main(string[] args)
{
var application = new WebApplicationBuilder()
.UseConfiguration(WebApplicationConfiguration.GetDefault(args))
.UseStartup<Startup>()
.Build();
application.Run();
}
} }
} }

View File

@ -0,0 +1,3 @@
{
"server": "Microsoft.AspNet.Server.Kestrel"
}

View File

@ -4,13 +4,14 @@
"Microsoft.AspNet.DataProtection": "1.0.0-*", "Microsoft.AspNet.DataProtection": "1.0.0-*",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-*", "Microsoft.AspNet.IISPlatformHandler": "1.0.0-*",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-*", "Microsoft.AspNet.Server.Kestrel": "1.0.0-*",
"Microsoft.AspNet.Server.WebListener": "1.0.0-*",
"Microsoft.Extensions.Caching.Memory": "1.0.0-*", "Microsoft.Extensions.Caching.Memory": "1.0.0-*",
"Microsoft.Extensions.Logging.Console": "1.0.0-*" "Microsoft.Extensions.Logging.Console": "1.0.0-*"
}, },
"compilationOptions": {
"emitEntryPoint": true
},
"commands": { "commands": {
"web": "Microsoft.AspNet.Server.Kestrel", "web": "CookieSessionSample"
"weblistener": "Microsoft.AspNet.Server.WebListener"
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "dnx451": { },

View File

@ -112,6 +112,14 @@ namespace JwtBearerSample
} }
// Entry point for the application. // Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args); public static void Main(string[] args)
{
var application = new WebApplicationBuilder()
.UseConfiguration(WebApplicationConfiguration.GetDefault(args))
.UseStartup<Startup>()
.Build();
application.Run();
}
} }
} }

View File

@ -0,0 +1,3 @@
{
"server": "Microsoft.AspNet.Server.Kestrel"
}

View File

@ -11,7 +11,7 @@
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-*" "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-*"
}, },
"commands": { "commands": {
"web": "Microsoft.AspNet.Server.Kestrel" "web": "JwtBearerSample"
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "dnx451": { },

View File

@ -15,17 +15,13 @@
"ASPNET_ENV": "Development" "ASPNET_ENV": "Development"
} }
}, },
"kestrel": {
"commandName": "kestrel",
"launchBrowser": true,
"launchUrl": "http://localhost:42023"
},
"web": { "web": {
"commandName": "web", "commandName": "web",
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "http://localhost:42023", "launchUrl": "http://localhost:42023",
"environmentVariables": { "environmentVariables": {
"Hosting:Environment": "Development" "Hosting:Environment": "Development",
"ASPNET_server.urls": "http://localhost:42023"
} }
} }
} }

View File

@ -2,6 +2,7 @@ using System.Linq;
using Microsoft.AspNet.Authentication.Cookies; using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.AspNet.Authentication.OpenIdConnect; using Microsoft.AspNet.Authentication.OpenIdConnect;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@ -63,5 +64,15 @@ namespace OpenIdConnectSample
await context.Response.WriteAsync("Hello Authenticated User"); await context.Response.WriteAsync("Hello Authenticated User");
}); });
} }
public static void Main(string[] args)
{
var application = new WebApplicationBuilder()
.UseConfiguration(WebApplicationConfiguration.GetDefault(args))
.UseStartup<Startup>()
.Build();
application.Run();
}
} }
} }

View File

@ -0,0 +1,3 @@
{
"server": "Microsoft.AspNet.Server.Kestrel"
}

View File

@ -4,7 +4,6 @@
"Microsoft.AspNet.Authentication.OpenIdConnect": "1.0.0-*", "Microsoft.AspNet.Authentication.OpenIdConnect": "1.0.0-*",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-*", "Microsoft.AspNet.IISPlatformHandler": "1.0.0-*",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-*", "Microsoft.AspNet.Server.Kestrel": "1.0.0-*",
"Microsoft.AspNet.Server.WebListener": "1.0.0-*",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-*", "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-*",
"Microsoft.Extensions.Logging.Console": "1.0.0-*" "Microsoft.Extensions.Logging.Console": "1.0.0-*"
}, },
@ -12,10 +11,11 @@
"dnx451": { }, "dnx451": { },
"dnxcore50": { } "dnxcore50": { }
}, },
"compilationOptions": {
"emitEntryPoint": true
},
"commands": { "commands": {
"web": "Microsoft.AspNet.Server.Kestrel", "web": "OpenIdConnectSample"
"kestrel": "Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:42023",
"weblistener": "Microsoft.AspNet.Server.WebListener --server.urls http://localhost:42023"
}, },
"userSecretsId": "aspnet5-OpenIdConnectSample-20151210110318" "userSecretsId": "aspnet5-OpenIdConnectSample-20151210110318"
} }

View File

@ -10,22 +10,17 @@
"profiles": { "profiles": {
"IIS Express": { "IIS Express": {
"commandName": "IISExpress", "commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": { "environmentVariables": {
"ASPNET_ENV": "Development" "ASPNET_ENV": "Development"
} }
}, },
"kestrel": {
"commandName": "kestrel",
"launchBrowser": true,
"launchUrl": "http://localhost:54540/"
},
"web": { "web": {
"commandName": "web", "commandName": "web",
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "http://localhost:54540/", "launchUrl": "http://localhost:54540/",
"environmentVariables": { "environmentVariables": {
"Hosting:Environment": "Development" "Hosting:Environment": "Development",
"ASPNET_server.urls": "http://localhost:54540/"
} }
} }
} }

View File

@ -12,6 +12,7 @@ using Microsoft.AspNet.Authentication.MicrosoftAccount;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Authentication.Twitter; using Microsoft.AspNet.Authentication.Twitter;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@ -160,7 +161,7 @@ namespace CookieSample
SaveTokensAsClaims = true SaveTokensAsClaims = true
}); });
// You must first create an app with live.com and add it's ID and Secret to your config.json or user-secrets. //// You must first create an app with live.com and add it's ID and Secret to your config.json or user-secrets.
app.UseMicrosoftAccountAuthentication(options => app.UseMicrosoftAccountAuthentication(options =>
{ {
options.DisplayName = "MicrosoftAccount - Requires project changes"; options.DisplayName = "MicrosoftAccount - Requires project changes";
@ -323,5 +324,15 @@ namespace CookieSample
await context.Response.WriteAsync("</body></html>"); await context.Response.WriteAsync("</body></html>");
}); });
} }
public static void Main(string[] args)
{
var application = new WebApplicationBuilder()
.UseConfiguration(WebApplicationConfiguration.GetDefault(args))
.UseStartup<Startup>()
.Build();
application.Run();
}
} }
} }

View File

@ -0,0 +1,3 @@
{
"server": "Microsoft.AspNet.Server.Kestrel"
}

View File

@ -8,14 +8,14 @@
"Microsoft.AspNet.DataProtection": "1.0.0-*", "Microsoft.AspNet.DataProtection": "1.0.0-*",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-*", "Microsoft.AspNet.IISPlatformHandler": "1.0.0-*",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-*", "Microsoft.AspNet.Server.Kestrel": "1.0.0-*",
"Microsoft.AspNet.Server.WebListener": "1.0.0-*",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-*", "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-*",
"Microsoft.Extensions.Logging.Console": "1.0.0-*" "Microsoft.Extensions.Logging.Console": "1.0.0-*"
}, },
"compilationOptions": {
"emitEntryPoint": true
},
"commands": { "commands": {
"web": "Microsoft.AspNet.Server.Kestrel", "web": "SocialSample"
"kestrel": "Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:54540",
"weblistener": "Microsoft.AspNet.Server.WebListener --server.urls=http://localhost:54540"
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "dnx451": { },

View File

@ -12,6 +12,7 @@ using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Features.Authentication; using Microsoft.AspNet.Http.Features.Authentication;
@ -748,12 +749,14 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task MapWillNotAffectChallenge() public async Task MapWillNotAffectChallenge()
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
.Configure(app =>
{ {
app.UseCookieAuthentication(options => options.LoginPath = new PathString("/page")); app.UseCookieAuthentication(options => options.LoginPath = new PathString("/page"));
app.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.ChallengeAsync("Cookies", new AuthenticationProperties() { RedirectUri = "/" }))); app.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.ChallengeAsync("Cookies", new AuthenticationProperties() { RedirectUri = "/" })));
}, })
services => services.AddAuthentication()); .ConfigureServices(services => services.AddAuthentication());
var server = new TestServer(builder);
var transaction = await server.SendAsync("http://example.com/login"); var transaction = await server.SendAsync("http://example.com/login");
@ -767,14 +770,17 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task ChallengeDoesNotSet401OnUnauthorized() public async Task ChallengeDoesNotSet401OnUnauthorized()
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication();
app.Run(async context =>
{ {
await Assert.ThrowsAsync<InvalidOperationException>(() => context.Authentication.ChallengeAsync()); app.UseCookieAuthentication();
}); app.Run(async context =>
}, services => services.AddAuthentication()); {
await Assert.ThrowsAsync<InvalidOperationException>(() => context.Authentication.ChallengeAsync());
});
})
.ConfigureServices(services => services.AddAuthentication());
var server = new TestServer(builder);
var transaction = await server.SendAsync("http://example.com"); var transaction = await server.SendAsync("http://example.com");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -783,12 +789,15 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task UseCookieWithInstanceDoesntUseSharedOptions() public async Task UseCookieWithInstanceDoesntUseSharedOptions()
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(options => options.CookieName = "One"); {
app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseCookieAuthentication(options => options.CookieName = "One");
app.Run(context => context.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity()))); app.UseCookieAuthentication(new CookieAuthenticationOptions());
}, services => services.AddAuthentication()); app.Run(context => context.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity())));
})
.ConfigureServices(services => services.AddAuthentication());
var server = new TestServer(builder);
var transaction = await server.SendAsync("http://example.com"); var transaction = await server.SendAsync("http://example.com");
@ -799,13 +808,15 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task MapWithSignInOnlyRedirectToReturnUrlOnLoginPath() public async Task MapWithSignInOnlyRedirectToReturnUrlOnLoginPath()
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(options => options.LoginPath = new PathString("/login")); {
app.Map("/notlogin", signoutApp => signoutApp.Run(context => context.Authentication.SignInAsync("Cookies", app.UseCookieAuthentication(options => options.LoginPath = new PathString("/login"));
new ClaimsPrincipal()))); app.Map("/notlogin", signoutApp => signoutApp.Run(context => context.Authentication.SignInAsync("Cookies",
}, new ClaimsPrincipal())));
services => services.AddAuthentication()); })
.ConfigureServices(services => services.AddAuthentication());
var server = new TestServer(builder);
var transaction = await server.SendAsync("http://example.com/notlogin?ReturnUrl=%2Fpage"); var transaction = await server.SendAsync("http://example.com/notlogin?ReturnUrl=%2Fpage");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -815,13 +826,15 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task MapWillNotAffectSignInRedirectToReturnUrl() public async Task MapWillNotAffectSignInRedirectToReturnUrl()
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(options => options.LoginPath = new PathString("/login")); {
app.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.SignInAsync("Cookies", app.UseCookieAuthentication(options => options.LoginPath = new PathString("/login"));
new ClaimsPrincipal()))); app.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.SignInAsync("Cookies",
}, new ClaimsPrincipal())));
services => services.AddAuthentication()); })
.ConfigureServices(services => services.AddAuthentication());
var server = new TestServer(builder);
var transaction = await server.SendAsync("http://example.com/login?ReturnUrl=%2Fpage"); var transaction = await server.SendAsync("http://example.com/login?ReturnUrl=%2Fpage");
@ -835,12 +848,14 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task MapWithSignOutOnlyRedirectToReturnUrlOnLogoutPath() public async Task MapWithSignOutOnlyRedirectToReturnUrlOnLogoutPath()
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(options => options.LogoutPath = new PathString("/logout")); {
app.Map("/notlogout", signoutApp => signoutApp.Run(context => context.Authentication.SignOutAsync("Cookies"))); app.UseCookieAuthentication(options => options.LogoutPath = new PathString("/logout"));
}, app.Map("/notlogout", signoutApp => signoutApp.Run(context => context.Authentication.SignOutAsync("Cookies")));
services => services.AddAuthentication()); })
.ConfigureServices(services => services.AddAuthentication());
var server = new TestServer(builder);
var transaction = await server.SendAsync("http://example.com/notlogout?ReturnUrl=%2Fpage"); var transaction = await server.SendAsync("http://example.com/notlogout?ReturnUrl=%2Fpage");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -850,12 +865,14 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task MapWillNotAffectSignOutRedirectToReturnUrl() public async Task MapWillNotAffectSignOutRedirectToReturnUrl()
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(options => options.LogoutPath = new PathString("/logout")); {
app.Map("/logout", signoutApp => signoutApp.Run(context => context.Authentication.SignOutAsync("Cookies"))); app.UseCookieAuthentication(options => options.LogoutPath = new PathString("/logout"));
}, app.Map("/logout", signoutApp => signoutApp.Run(context => context.Authentication.SignOutAsync("Cookies")));
services => services.AddAuthentication()); })
.ConfigureServices(services => services.AddAuthentication());
var server = new TestServer(builder);
var transaction = await server.SendAsync("http://example.com/logout?ReturnUrl=%2Fpage"); var transaction = await server.SendAsync("http://example.com/logout?ReturnUrl=%2Fpage");
@ -869,12 +886,14 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task MapWillNotAffectAccessDenied() public async Task MapWillNotAffectAccessDenied()
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
.Configure(app =>
{ {
app.UseCookieAuthentication(options => options.AccessDeniedPath = new PathString("/denied")); app.UseCookieAuthentication(options => options.AccessDeniedPath = new PathString("/denied"));
app.Map("/forbid", signoutApp => signoutApp.Run(context => context.Authentication.ForbidAsync("Cookies"))); app.Map("/forbid", signoutApp => signoutApp.Run(context => context.Authentication.ForbidAsync("Cookies")));
}, })
services => services.AddAuthentication()); .ConfigureServices(services => services.AddAuthentication());
var server = new TestServer(builder);
var transaction = await server.SendAsync("http://example.com/forbid"); var transaction = await server.SendAsync("http://example.com/forbid");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
@ -886,13 +905,15 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task NestedMapWillNotAffectLogin() public async Task NestedMapWillNotAffectLogin()
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
app.Map("/base", map => .Configure(app =>
{ app.Map("/base", map =>
map.UseCookieAuthentication(options => options.LoginPath = new PathString("/page")); {
map.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.ChallengeAsync("Cookies", new AuthenticationProperties() { RedirectUri = "/" }))); map.UseCookieAuthentication(options => options.LoginPath = new PathString("/page"));
}), map.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.ChallengeAsync("Cookies", new AuthenticationProperties() { RedirectUri = "/" })));
services => services.AddAuthentication()); }))
.ConfigureServices(services => services.AddAuthentication());
var server = new TestServer(builder);
var transaction = await server.SendAsync("http://example.com/base/login"); var transaction = await server.SendAsync("http://example.com/base/login");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
@ -905,13 +926,15 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task NestedMapWillNotAffectAccessDenied() public async Task NestedMapWillNotAffectAccessDenied()
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
app.Map("/base", map => .Configure(app =>
{ app.Map("/base", map =>
map.UseCookieAuthentication(options => options.AccessDeniedPath = new PathString("/denied")); {
map.Map("/forbid", signoutApp => signoutApp.Run(context => context.Authentication.ForbidAsync("Cookies"))); map.UseCookieAuthentication(options => options.AccessDeniedPath = new PathString("/denied"));
}), map.Map("/forbid", signoutApp => signoutApp.Run(context => context.Authentication.ForbidAsync("Cookies")));
services => services.AddAuthentication()); }))
.ConfigureServices(services => services.AddAuthentication());
var server = new TestServer(builder);
var transaction = await server.SendAsync("http://example.com/base/forbid"); var transaction = await server.SendAsync("http://example.com/base/forbid");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
@ -925,39 +948,43 @@ namespace Microsoft.AspNet.Authentication.Cookies
{ {
var dp = new NoOpDataProtector(); var dp = new NoOpDataProtector();
var server1 = TestServer.Create(app => var builder1 = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(options =>
{ {
options.TicketDataFormat = new TicketDataFormat(dp); app.UseCookieAuthentication(options =>
options.CookieName = "Cookie"; {
}); options.TicketDataFormat = new TicketDataFormat(dp);
app.Use((context, next) => options.CookieName = "Cookie";
context.Authentication.SignInAsync("Cookies", });
new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))), app.Use((context, next) =>
new AuthenticationProperties())); context.Authentication.SignInAsync("Cookies",
}, new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))),
services => services.AddAuthentication()); new AuthenticationProperties()));
})
.ConfigureServices(services => services.AddAuthentication());
var server1 = new TestServer(builder1);
var transaction = await SendAsync(server1, "http://example.com/stuff"); var transaction = await SendAsync(server1, "http://example.com/stuff");
Assert.NotNull(transaction.SetCookie); Assert.NotNull(transaction.SetCookie);
var server2 = TestServer.Create(app => var builder2 = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(options =>
{ {
options.AuthenticationScheme = "Cookies"; app.UseCookieAuthentication(options =>
options.CookieName = "Cookie"; {
options.TicketDataFormat = new TicketDataFormat(dp); options.AuthenticationScheme = "Cookies";
}); options.CookieName = "Cookie";
app.Use(async (context, next) => options.TicketDataFormat = new TicketDataFormat(dp);
{ });
var authContext = new AuthenticateContext("Cookies"); app.Use(async (context, next) =>
await context.Authentication.AuthenticateAsync(authContext); {
Describe(context.Response, authContext); var authContext = new AuthenticateContext("Cookies");
}); await context.Authentication.AuthenticateAsync(authContext);
}, Describe(context.Response, authContext);
services => services.AddAuthentication()); });
})
.ConfigureServices(services => services.AddAuthentication());
var server2 = new TestServer(builder2);
var transaction2 = await SendAsync(server2, "http://example.com/stuff", transaction.CookieNameValue); var transaction2 = await SendAsync(server2, "http://example.com/stuff", transaction.CookieNameValue);
Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name)); Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));
} }
@ -1003,71 +1030,73 @@ namespace Microsoft.AspNet.Authentication.Cookies
private static TestServer CreateServer(Action<CookieAuthenticationOptions> configureOptions, Func<HttpContext, Task> testpath = null, Uri baseAddress = null, Action<ClaimsTransformationOptions> claimsTransform = null) private static TestServer CreateServer(Action<CookieAuthenticationOptions> configureOptions, Func<HttpContext, Task> testpath = null, Uri baseAddress = null, Action<ClaimsTransformationOptions> claimsTransform = null)
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(configureOptions); {
// app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie2" }); app.UseCookieAuthentication(configureOptions);
// app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie2" });
if (claimsTransform != null) if (claimsTransform != null)
{
app.UseClaimsTransformation(claimsTransform);
}
app.Use(async (context, next) =>
{
var req = context.Request;
var res = context.Response;
PathString remainder;
if (req.Path == new PathString("/normal"))
{ {
res.StatusCode = 200; app.UseClaimsTransformation(claimsTransform);
} }
else if (req.Path == new PathString("/protected")) app.Use(async (context, next) =>
{ {
res.StatusCode = 401; var req = context.Request;
} var res = context.Response;
else if (req.Path == new PathString("/forbid")) // Simulate forbidden PathString remainder;
{ if (req.Path == new PathString("/normal"))
await context.Authentication.ForbidAsync(CookieAuthenticationDefaults.AuthenticationScheme); {
} res.StatusCode = 200;
else if (req.Path == new PathString("/challenge")) }
{ else if (req.Path == new PathString("/protected"))
await context.Authentication.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme); {
} res.StatusCode = 401;
else if (req.Path == new PathString("/signout")) }
{ else if (req.Path == new PathString("/forbid")) // Simulate forbidden
await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); {
} await context.Authentication.ForbidAsync(CookieAuthenticationDefaults.AuthenticationScheme);
else if (req.Path == new PathString("/unauthorized")) }
{ else if (req.Path == new PathString("/challenge"))
await context.Authentication.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme, new AuthenticationProperties(), ChallengeBehavior.Unauthorized); {
} await context.Authentication.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme);
else if (req.Path == new PathString("/protected/CustomRedirect")) }
{ else if (req.Path == new PathString("/signout"))
await context.Authentication.ChallengeAsync(new AuthenticationProperties() { RedirectUri = "/CustomRedirect" }); {
} await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
else if (req.Path == new PathString("/me")) }
{ else if (req.Path == new PathString("/unauthorized"))
var authContext = new AuthenticateContext(CookieAuthenticationDefaults.AuthenticationScheme); {
authContext.Authenticated(context.User, properties: null, description: null); await context.Authentication.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme, new AuthenticationProperties(), ChallengeBehavior.Unauthorized);
Describe(res, authContext); }
} else if (req.Path == new PathString("/protected/CustomRedirect"))
else if (req.Path.StartsWithSegments(new PathString("/me"), out remainder)) {
{ await context.Authentication.ChallengeAsync(new AuthenticationProperties() { RedirectUri = "/CustomRedirect" });
var authContext = new AuthenticateContext(remainder.Value.Substring(1)); }
await context.Authentication.AuthenticateAsync(authContext); else if (req.Path == new PathString("/me"))
Describe(res, authContext); {
} var authContext = new AuthenticateContext(CookieAuthenticationDefaults.AuthenticationScheme);
else if (req.Path == new PathString("/testpath") && testpath != null) authContext.Authenticated(context.User, properties: null, description: null);
{ Describe(res, authContext);
await testpath(context); }
} else if (req.Path.StartsWithSegments(new PathString("/me"), out remainder))
else {
{ var authContext = new AuthenticateContext(remainder.Value.Substring(1));
await next(); await context.Authentication.AuthenticateAsync(authContext);
} Describe(res, authContext);
}); }
}, else if (req.Path == new PathString("/testpath") && testpath != null)
services => services.AddAuthentication()); {
await testpath(context);
}
else
{
await next();
}
});
})
.ConfigureServices(services => services.AddAuthentication());
var server = new TestServer(builder);
server.BaseAddress = baseAddress; server.BaseAddress = baseAddress;
return server; return server;
} }

View File

@ -2,7 +2,6 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
@ -13,6 +12,7 @@ using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.TestHost; using Microsoft.AspNet.TestHost;
@ -226,21 +226,23 @@ namespace Microsoft.AspNet.Authentication.Facebook
private static TestServer CreateServer(Action<IApplicationBuilder> configure, Action<IServiceCollection> configureServices, Func<HttpContext, bool> handler) private static TestServer CreateServer(Action<IApplicationBuilder> configure, Action<IServiceCollection> configureServices, Func<HttpContext, bool> handler)
{ {
return TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
if (configure != null)
{ {
configure(app); if (configure != null)
}
app.Use(async (context, next) =>
{
if (handler == null || !handler(context))
{ {
await next(); configure(app);
} }
}); app.Use(async (context, next) =>
}, {
configureServices); if (handler == null || !handler(context))
{
await next();
}
});
})
.ConfigureServices(configureServices);
return new TestServer(builder);
} }
} }
} }

View File

@ -12,6 +12,7 @@ using System.Threading.Tasks;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Features.Authentication; using Microsoft.AspNet.Http.Features.Authentication;
@ -765,74 +766,76 @@ namespace Microsoft.AspNet.Authentication.Google
private static TestServer CreateServer(Action<GoogleOptions> configureOptions, Func<HttpContext, Task> testpath = null) private static TestServer CreateServer(Action<GoogleOptions> configureOptions, Func<HttpContext, Task> testpath = null)
{ {
return TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(options =>
{ {
options.AuthenticationScheme = TestExtensions.CookieAuthenticationScheme; app.UseCookieAuthentication(options =>
options.AutomaticAuthenticate = true; {
}); options.AuthenticationScheme = TestExtensions.CookieAuthenticationScheme;
app.UseGoogleAuthentication(configureOptions); options.AutomaticAuthenticate = true;
app.UseClaimsTransformation(p => });
app.UseGoogleAuthentication(configureOptions);
app.UseClaimsTransformation(p =>
{
var id = new ClaimsIdentity("xform");
id.AddClaim(new Claim("xform", "yup"));
p.AddIdentity(id);
return Task.FromResult(p);
});
app.Use(async (context, next) =>
{
var req = context.Request;
var res = context.Response;
if (req.Path == new PathString("/challenge"))
{
await context.Authentication.ChallengeAsync("Google");
}
else if (req.Path == new PathString("/me"))
{
res.Describe(context.User);
}
else if (req.Path == new PathString("/unauthorized"))
{
// Simulate Authorization failure
var result = await context.Authentication.AuthenticateAsync("Google");
await context.Authentication.ChallengeAsync("Google");
}
else if (req.Path == new PathString("/unauthorizedAuto"))
{
var result = await context.Authentication.AuthenticateAsync("Google");
await context.Authentication.ChallengeAsync();
}
else if (req.Path == new PathString("/401"))
{
res.StatusCode = 401;
}
else if (req.Path == new PathString("/signIn"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync("Google", new ClaimsPrincipal()));
}
else if (req.Path == new PathString("/signOut"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync("Google"));
}
else if (req.Path == new PathString("/forbid"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.ForbidAsync("Google"));
}
else if (testpath != null)
{
await testpath(context);
}
else
{
await next();
}
});
})
.ConfigureServices(services =>
{ {
var id = new ClaimsIdentity("xform"); services.AddAuthentication(options => options.SignInScheme = TestExtensions.CookieAuthenticationScheme);
id.AddClaim(new Claim("xform", "yup"));
p.AddIdentity(id);
return Task.FromResult(p);
}); });
app.Use(async (context, next) => return new TestServer(builder);
{
var req = context.Request;
var res = context.Response;
if (req.Path == new PathString("/challenge"))
{
await context.Authentication.ChallengeAsync("Google");
}
else if (req.Path == new PathString("/me"))
{
res.Describe(context.User);
}
else if (req.Path == new PathString("/unauthorized"))
{
// Simulate Authorization failure
var result = await context.Authentication.AuthenticateAsync("Google");
await context.Authentication.ChallengeAsync("Google");
}
else if (req.Path == new PathString("/unauthorizedAuto"))
{
var result = await context.Authentication.AuthenticateAsync("Google");
await context.Authentication.ChallengeAsync();
}
else if (req.Path == new PathString("/401"))
{
res.StatusCode = 401;
}
else if (req.Path == new PathString("/signIn"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync("Google", new ClaimsPrincipal()));
}
else if (req.Path == new PathString("/signOut"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync("Google"));
}
else if (req.Path == new PathString("/forbid"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.ForbidAsync("Google"));
}
else if (testpath != null)
{
await testpath(context);
}
else
{
await next();
}
});
},
services =>
{
services.AddAuthentication(options => options.SignInScheme = TestExtensions.CookieAuthenticationScheme);
});
} }
} }
} }

View File

@ -9,6 +9,7 @@ using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Features.Authentication; using Microsoft.AspNet.Http.Features.Authentication;
@ -536,67 +537,69 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
private static TestServer CreateServer(Action<JwtBearerOptions> configureOptions, Func<HttpContext, bool> handler = null) private static TestServer CreateServer(Action<JwtBearerOptions> configureOptions, Func<HttpContext, bool> handler = null)
{ {
return TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
if (configureOptions != null)
{ {
app.UseJwtBearerAuthentication(configureOptions); if (configureOptions != null)
}
app.Use(async (context, next) =>
{
if (context.Request.Path == new PathString("/checkforerrors"))
{ {
var authContext = new AuthenticateContext(Http.Authentication.AuthenticationManager.AutomaticScheme); app.UseJwtBearerAuthentication(configureOptions);
await context.Authentication.AuthenticateAsync(authContext);
if (authContext.Error != null)
{
throw new Exception("Failed to authenticate", authContext.Error);
}
return;
} }
else if (context.Request.Path == new PathString("/oauth"))
{
if (context.User == null ||
context.User.Identity == null ||
!context.User.Identity.IsAuthenticated)
{
context.Response.StatusCode = 401;
app.Use(async (context, next) =>
{
if (context.Request.Path == new PathString("/checkforerrors"))
{
var authContext = new AuthenticateContext(Http.Authentication.AuthenticationManager.AutomaticScheme);
await context.Authentication.AuthenticateAsync(authContext);
if (authContext.Error != null)
{
throw new Exception("Failed to authenticate", authContext.Error);
}
return; return;
} }
else if (context.Request.Path == new PathString("/oauth"))
var identifier = context.User.FindFirst(ClaimTypes.NameIdentifier);
if (identifier == null)
{ {
context.Response.StatusCode = 500; if (context.User == null ||
context.User.Identity == null ||
!context.User.Identity.IsAuthenticated)
{
context.Response.StatusCode = 401;
return; return;
}
var identifier = context.User.FindFirst(ClaimTypes.NameIdentifier);
if (identifier == null)
{
context.Response.StatusCode = 500;
return;
}
await context.Response.WriteAsync(identifier.Value);
} }
else if (context.Request.Path == new PathString("/unauthorized"))
await context.Response.WriteAsync(identifier.Value); {
} // Simulate Authorization failure
else if (context.Request.Path == new PathString("/unauthorized")) var result = await context.Authentication.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
{ await context.Authentication.ChallengeAsync(JwtBearerDefaults.AuthenticationScheme);
// Simulate Authorization failure }
var result = await context.Authentication.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme); else if (context.Request.Path == new PathString("/signIn"))
await context.Authentication.ChallengeAsync(JwtBearerDefaults.AuthenticationScheme); {
} await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync(JwtBearerDefaults.AuthenticationScheme, new ClaimsPrincipal()));
else if (context.Request.Path == new PathString("/signIn")) }
{ else if (context.Request.Path == new PathString("/signOut"))
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync(JwtBearerDefaults.AuthenticationScheme, new ClaimsPrincipal())); {
} await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync(JwtBearerDefaults.AuthenticationScheme));
else if (context.Request.Path == new PathString("/signOut")) }
{ else
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync(JwtBearerDefaults.AuthenticationScheme)); {
} await next();
else }
{ });
await next(); })
} .ConfigureServices(services => services.AddAuthentication());
}); return new TestServer(builder);
},
services => services.AddAuthentication());
} }
// TODO: see if we can share the TestExtensions SendAsync method (only diff is auth header) // TODO: see if we can share the TestExtensions SendAsync method (only diff is auth header)

View File

@ -12,6 +12,7 @@ using Microsoft.AspNet.Authentication.MicrosoftAccount;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.TestHost; using Microsoft.AspNet.TestHost;
@ -177,53 +178,55 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount
private static TestServer CreateServer(Action<MicrosoftAccountOptions> configureOptions) private static TestServer CreateServer(Action<MicrosoftAccountOptions> configureOptions)
{ {
return TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(options =>
{ {
options.AuthenticationScheme = TestExtensions.CookieAuthenticationScheme; app.UseCookieAuthentication(options =>
options.AutomaticAuthenticate = true; {
}); options.AuthenticationScheme = TestExtensions.CookieAuthenticationScheme;
app.UseMicrosoftAccountAuthentication(configureOptions); options.AutomaticAuthenticate = true;
});
app.UseMicrosoftAccountAuthentication(configureOptions);
app.Use(async (context, next) => app.Use(async (context, next) =>
{
var req = context.Request;
var res = context.Response;
if (req.Path == new PathString("/challenge"))
{
await context.Authentication.ChallengeAsync("Microsoft");
}
else if (req.Path == new PathString("/me"))
{
res.Describe(context.User);
}
else if (req.Path == new PathString("/signIn"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync("Microsoft", new ClaimsPrincipal()));
}
else if (req.Path == new PathString("/signOut"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync("Microsoft"));
}
else if (req.Path == new PathString("/forbid"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.ForbidAsync("Microsoft"));
}
else
{
await next();
}
});
})
.ConfigureServices(services =>
{ {
var req = context.Request; services.AddAuthentication();
var res = context.Response; services.Configure<SharedAuthenticationOptions>(options =>
if (req.Path == new PathString("/challenge"))
{ {
await context.Authentication.ChallengeAsync("Microsoft"); options.SignInScheme = TestExtensions.CookieAuthenticationScheme;
} });
else if (req.Path == new PathString("/me"))
{
res.Describe(context.User);
}
else if (req.Path == new PathString("/signIn"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync("Microsoft", new ClaimsPrincipal()));
}
else if (req.Path == new PathString("/signOut"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync("Microsoft"));
}
else if (req.Path == new PathString("/forbid"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.ForbidAsync("Microsoft"));
}
else
{
await next();
}
}); });
}, return new TestServer(builder);
services =>
{
services.AddAuthentication();
services.Configure<SharedAuthenticationOptions>(options =>
{
options.SignInScheme = TestExtensions.CookieAuthenticationScheme;
});
});
} }
private static HttpResponseMessage ReturnJsonResponse(object content) private static HttpResponseMessage ReturnJsonResponse(object content)

View File

@ -12,6 +12,7 @@ using System.Text.Encodings.Web;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Authentication.OpenIdConnect; using Microsoft.AspNet.Authentication.OpenIdConnect;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.TestHost; using Microsoft.AspNet.TestHost;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -94,8 +95,8 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
private static TestServer CreateServer(Action<OpenIdConnectOptions> configureOptions, UrlEncoder encoder, OpenIdConnectHandler handler = null) private static TestServer CreateServer(Action<OpenIdConnectOptions> configureOptions, UrlEncoder encoder, OpenIdConnectHandler handler = null)
{ {
return TestServer.Create( var builder = new WebApplicationBuilder()
app => .Configure(app =>
{ {
var options = new OpenIdConnectOptions(); var options = new OpenIdConnectOptions();
configureOptions(options); configureOptions(options);
@ -104,13 +105,13 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
{ {
await next(); await next();
}); });
}, })
services => .ConfigureServices(services =>
{ {
services.AddWebEncoders(); services.AddWebEncoders();
services.AddDataProtection(); services.AddDataProtection();
} });
); return new TestServer(builder);
} }
} }
} }

View File

@ -14,6 +14,7 @@ using System.Xml.Linq;
using Microsoft.AspNet.Authentication.Cookies; using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.AspNet.Authentication.OpenIdConnect; using Microsoft.AspNet.Authentication.OpenIdConnect;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.TestHost; using Microsoft.AspNet.TestHost;
@ -380,63 +381,65 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
private static TestServer CreateServer(Action<OpenIdConnectOptions> configureOptions, Func<HttpContext, Task> handler = null, AuthenticationProperties properties = null) private static TestServer CreateServer(Action<OpenIdConnectOptions> configureOptions, Func<HttpContext, Task> handler = null, AuthenticationProperties properties = null)
{ {
return TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(options =>
{ {
options.AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme; app.UseCookieAuthentication(options =>
}); {
app.UseOpenIdConnectAuthentication(configureOptions); options.AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;
app.Use(async (context, next) => });
{ app.UseOpenIdConnectAuthentication(configureOptions);
var req = context.Request; app.Use(async (context, next) =>
var res = context.Response; {
var req = context.Request;
var res = context.Response;
if (req.Path == new PathString(Challenge)) if (req.Path == new PathString(Challenge))
{ {
await context.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme); await context.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme);
} }
else if (req.Path == new PathString(ChallengeWithProperties)) else if (req.Path == new PathString(ChallengeWithProperties))
{ {
await context.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, properties); await context.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, properties);
} }
else if (req.Path == new PathString(ChallengeWithOutContext)) else if (req.Path == new PathString(ChallengeWithOutContext))
{ {
res.StatusCode = 401; res.StatusCode = 401;
} }
else if (req.Path == new PathString(Signin)) else if (req.Path == new PathString(Signin))
{ {
// REVIEW: this used to just be res.SignIn() // REVIEW: this used to just be res.SignIn()
await context.Authentication.SignInAsync(OpenIdConnectDefaults.AuthenticationScheme, new ClaimsPrincipal()); await context.Authentication.SignInAsync(OpenIdConnectDefaults.AuthenticationScheme, new ClaimsPrincipal());
} }
else if (req.Path == new PathString(Signout)) else if (req.Path == new PathString(Signout))
{ {
await context.Authentication.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme); await context.Authentication.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
} }
else if (req.Path == new PathString("/signout_with_specific_redirect_uri")) else if (req.Path == new PathString("/signout_with_specific_redirect_uri"))
{ {
await context.Authentication.SignOutAsync( await context.Authentication.SignOutAsync(
OpenIdConnectDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme,
new AuthenticationProperties() { RedirectUri = "http://www.example.com/specific_redirect_uri" }); new AuthenticationProperties() { RedirectUri = "http://www.example.com/specific_redirect_uri" });
} }
else if (handler != null) else if (handler != null)
{ {
await handler(context); await handler(context);
} }
else else
{ {
await next(); await next();
} }
}); });
}, })
services => .ConfigureServices(services =>
{
services.AddAuthentication();
services.Configure<SharedAuthenticationOptions>(options =>
{ {
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; services.AddAuthentication();
services.Configure<SharedAuthenticationOptions>(options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
}); });
}); return new TestServer(builder);
} }
private static async Task<Transaction> SendAsync(TestServer server, string uri, string cookieHeader = null) private static async Task<Transaction> SendAsync(TestServer server, string uri, string cookieHeader = null)

View File

@ -1,17 +1,16 @@
// Copyright (c) .NET Foundation. All rights reserved. See License.txt in the project root for license information. // Copyright (c) .NET Foundation. All rights reserved. See License.txt in the project root for license information.
using System; using System;
using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Security.Claims; using System.Security.Claims;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.TestHost; using Microsoft.AspNet.TestHost;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.WebEncoders;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Authentication.Twitter namespace Microsoft.AspNet.Authentication.Twitter
@ -153,43 +152,45 @@ namespace Microsoft.AspNet.Authentication.Twitter
private static TestServer CreateServer(Action<TwitterOptions> configure, Func<HttpContext, bool> handler = null) private static TestServer CreateServer(Action<TwitterOptions> configure, Func<HttpContext, bool> handler = null)
{ {
return TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(options =>
{ {
options.AuthenticationScheme = "External"; app.UseCookieAuthentication(options =>
}); {
app.UseTwitterAuthentication(configure); options.AuthenticationScheme = "External";
app.Use(async (context, next) => });
app.UseTwitterAuthentication(configure);
app.Use(async (context, next) =>
{
var req = context.Request;
var res = context.Response;
if (req.Path == new PathString("/signIn"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync("Twitter", new ClaimsPrincipal()));
}
else if (req.Path == new PathString("/signOut"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync("Twitter"));
}
else if (req.Path == new PathString("/forbid"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.ForbidAsync("Twitter"));
}
else if (handler == null || !handler(context))
{
await next();
}
});
})
.ConfigureServices(services =>
{ {
var req = context.Request; services.AddAuthentication();
var res = context.Response; services.Configure<SharedAuthenticationOptions>(options =>
if (req.Path == new PathString("/signIn"))
{ {
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync("Twitter", new ClaimsPrincipal())); options.SignInScheme = "External";
} });
else if (req.Path == new PathString("/signOut"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync("Twitter"));
}
else if (req.Path == new PathString("/forbid"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.ForbidAsync("Twitter"));
}
else if (handler == null || !handler(context))
{
await next();
}
}); });
}, return new TestServer(builder);
services =>
{
services.AddAuthentication();
services.Configure<SharedAuthenticationOptions>(options =>
{
options.SignInScheme = "External";
});
});
} }
} }
} }

View File

@ -4,6 +4,7 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features; using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Http.Features.Internal; using Microsoft.AspNet.Http.Features.Internal;
@ -129,18 +130,20 @@ namespace Microsoft.AspNet.CookiePolicy.Test
[Fact] [Fact]
public async Task CookiePolicyCanHijackAppend() public async Task CookiePolicyCanHijackAppend()
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookiePolicy(options => options.OnAppendCookie = ctx => ctx.CookieName = ctx.CookieValue = "Hao");
app.Run(context =>
{ {
context.Response.Cookies.Append("A", "A"); app.UseCookiePolicy(options => options.OnAppendCookie = ctx => ctx.CookieName = ctx.CookieValue = "Hao");
context.Response.Cookies.Append("B", "B", new CookieOptions { Secure = false }); app.Run(context =>
context.Response.Cookies.Append("C", "C", new CookieOptions()); {
context.Response.Cookies.Append("D", "D", new CookieOptions { Secure = true }); context.Response.Cookies.Append("A", "A");
return Task.FromResult(0); context.Response.Cookies.Append("B", "B", new CookieOptions { Secure = false });
context.Response.Cookies.Append("C", "C", new CookieOptions());
context.Response.Cookies.Append("D", "D", new CookieOptions { Secure = true });
return Task.FromResult(0);
});
}); });
}); var server = new TestServer(builder);
var transaction = await server.SendAsync("http://example.com/login"); var transaction = await server.SendAsync("http://example.com/login");
@ -154,7 +157,8 @@ namespace Microsoft.AspNet.CookiePolicy.Test
[Fact] [Fact]
public async Task CookiePolicyCanHijackDelete() public async Task CookiePolicyCanHijackDelete()
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
.Configure(app =>
{ {
app.UseCookiePolicy(options => options.OnDeleteCookie = ctx => ctx.CookieName = "A"); app.UseCookiePolicy(options => options.OnDeleteCookie = ctx => ctx.CookieName = "A");
app.Run(context => app.Run(context =>
@ -166,6 +170,7 @@ namespace Microsoft.AspNet.CookiePolicy.Test
return Task.FromResult(0); return Task.FromResult(0);
}); });
}); });
var server = new TestServer(builder);
var transaction = await server.SendAsync("http://example.com/login"); var transaction = await server.SendAsync("http://example.com/login");
@ -177,7 +182,8 @@ namespace Microsoft.AspNet.CookiePolicy.Test
[Fact] [Fact]
public async Task CookiePolicyCallsCookieFeature() public async Task CookiePolicyCallsCookieFeature()
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
.Configure(app =>
{ {
app.Use(next => context => app.Use(next => context =>
{ {
@ -194,6 +200,7 @@ namespace Microsoft.AspNet.CookiePolicy.Test
return context.Response.WriteAsync("Done"); return context.Response.WriteAsync("Done");
}); });
}); });
var server = new TestServer(builder);
var transaction = await server.SendAsync("http://example.com/login"); var transaction = await server.SendAsync("http://example.com/login");
Assert.Equal("Done", transaction.ResponseText); Assert.Equal("Done", transaction.ResponseText);
@ -251,7 +258,8 @@ namespace Microsoft.AspNet.CookiePolicy.Test
RequestDelegate configureSetup, RequestDelegate configureSetup,
params RequestTest[] tests) params RequestTest[] tests)
{ {
var server = TestServer.Create(app => var builder = new WebApplicationBuilder()
.Configure(app =>
{ {
app.Map(path, map => app.Map(path, map =>
{ {
@ -259,6 +267,7 @@ namespace Microsoft.AspNet.CookiePolicy.Test
map.Run(configureSetup); map.Run(configureSetup);
}); });
}); });
var server = new TestServer(builder);
foreach (var test in tests) foreach (var test in tests)
{ {
await test.Execute(server); await test.Execute(server);

View File

@ -13,6 +13,7 @@ using System.Xml;
using System.Xml.Linq; using System.Xml.Linq;
using Microsoft.AspNet.Authentication; using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Owin; using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.Cookies;
@ -120,15 +121,18 @@ namespace Microsoft.AspNet.CookiePolicy.Test
var transaction = await SendAsync(interopServer, "http://example.com"); var transaction = await SendAsync(interopServer, "http://example.com");
var newServer = TestHost.TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(options => options.DataProtectionProvider = dataProtection);
app.Run(async context =>
{ {
var result = await context.Authentication.AuthenticateAsync("Cookies"); app.UseCookieAuthentication(options => options.DataProtectionProvider = dataProtection);
await context.Response.WriteAsync(result.Identity.Name); app.Run(async context =>
}); {
}, services => services.AddAuthentication()); var result = await context.Authentication.AuthenticateAsync("Cookies");
await context.Response.WriteAsync(result.Identity.Name);
});
})
.ConfigureServices(services => services.AddAuthentication());
var newServer = new TestHost.TestServer(builder);
var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com/login"); var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com/login");
request.Headers.Add("Cookie", transaction.SetCookie.Split(new[] { ';' }, 2).First()); request.Headers.Add("Cookie", transaction.SetCookie.Split(new[] { ';' }, 2).First());
@ -146,11 +150,14 @@ namespace Microsoft.AspNet.CookiePolicy.Test
user.AddIdentity(identity); user.AddIdentity(identity);
var dataProtection = new DataProtection.DataProtectionProvider(new DirectoryInfo("..\\..\\artifacts")); var dataProtection = new DataProtection.DataProtectionProvider(new DirectoryInfo("..\\..\\artifacts"));
var newServer = TestHost.TestServer.Create(app => var builder = new WebApplicationBuilder()
{ .Configure(app =>
app.UseCookieAuthentication(options => options.DataProtectionProvider = dataProtection); {
app.Run(context => context.Authentication.SignInAsync("Cookies", user)); app.UseCookieAuthentication(options => options.DataProtectionProvider = dataProtection);
}, services => services.AddAuthentication()); app.Run(context => context.Authentication.SignInAsync("Cookies", user));
})
.ConfigureServices(services => services.AddAuthentication());
var newServer = new TestHost.TestServer(builder);
var cookie = await SendAndGetCookie(newServer, "http://example.com/login"); var cookie = await SendAndGetCookie(newServer, "http://example.com/login");