Updating to new options pattern

This commit is contained in:
John Luo 2016-01-06 13:58:30 -08:00
parent 990e412326
commit 417ca6cbe3
91 changed files with 838 additions and 840 deletions

View File

@ -20,9 +20,9 @@ namespace CookieSample
{ {
loggerfactory.AddConsole(LogLevel.Information); loggerfactory.AddConsole(LogLevel.Information);
app.UseCookieAuthentication(options => app.UseCookieAuthentication(new CookieAuthenticationOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true
}); });
app.Run(async context => app.Run(async context =>

View File

@ -21,10 +21,10 @@ namespace CookieSessionSample
{ {
loggerfactory.AddConsole(LogLevel.Information); loggerfactory.AddConsole(LogLevel.Information);
app.UseCookieAuthentication(options => app.UseCookieAuthentication(new CookieAuthenticationOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
options.SessionStore = new MemoryCacheTicketStore(); SessionStore = new MemoryCacheTicketStore()
}); });
app.Run(async context => app.Run(async context =>

View File

@ -59,13 +59,13 @@ namespace JwtBearerSample
app.UseDefaultFiles(); app.UseDefaultFiles();
app.UseStaticFiles(); app.UseStaticFiles();
app.UseJwtBearerAuthentication(options => app.UseJwtBearerAuthentication(new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
options.AutomaticChallenge = true; AutomaticChallenge = true,
// You also need to update /wwwroot/app/scripts/app.js // You also need to update /wwwroot/app/scripts/app.js
options.Authority = Configuration["jwt:authority"]; Authority = Configuration["jwt:authority"],
options.Audience = Configuration["jwt:audience"]; Audience = Configuration["jwt:audience"]
}); });
// [Authorize] would usually handle this // [Authorize] would usually handle this

View File

@ -35,18 +35,18 @@ namespace OpenIdConnectSample
app.UseIISPlatformHandler(); app.UseIISPlatformHandler();
app.UseCookieAuthentication(options => app.UseCookieAuthentication(new CookieAuthenticationOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true
}); });
app.UseOpenIdConnectAuthentication(options => app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{ {
options.ClientId = Configuration["oidc:clientid"]; ClientId = Configuration["oidc:clientid"],
options.ClientSecret = Configuration["oidc:clientsecret"]; // for code flow ClientSecret = Configuration["oidc:clientsecret"], // for code flow
options.Authority = Configuration["oidc:authority"]; Authority = Configuration["oidc:authority"],
options.ResponseType = OpenIdConnectResponseTypes.Code; ResponseType = OpenIdConnectResponseTypes.Code,
options.GetClaimsFromUserInfoEndpoint = true; GetClaimsFromUserInfoEndpoint = true
}); });
app.Run(async context => app.Run(async context =>

View File

@ -63,47 +63,44 @@ namespace CookieSample
} }
}); });
app.UseCookieAuthentication(options => app.UseCookieAuthentication(new CookieAuthenticationOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
options.AutomaticChallenge = true; AutomaticChallenge = true,
options.LoginPath = new PathString("/login"); LoginPath = new PathString("/login")
}); });
// You must first create an app with facebook and add it's ID and Secret to your config.json or user-secrets. // You must first create an app with facebook and add it's ID and Secret to your config.json or user-secrets.
// https://developers.facebook.com/apps/ // https://developers.facebook.com/apps/
app.UseFacebookAuthentication(options => app.UseFacebookAuthentication(new FacebookOptions
{ {
options.AppId = Configuration["facebook:appid"]; AppId = Configuration["facebook:appid"],
options.AppSecret = Configuration["facebook:appsecret"]; AppSecret = Configuration["facebook:appsecret"],
options.Scope.Add("email"); Scope = { "email" },
options.Fields.Add("name"); Fields = { "name", "email" }
options.Fields.Add("email");
}); });
// See config.json // See config.json
app.UseOAuthAuthentication(options => app.UseOAuthAuthentication(new OAuthOptions
{ {
options.AuthenticationScheme = "Google-AccessToken"; AuthenticationScheme = "Google-AccessToken",
options.DisplayName = "Google-AccessToken"; DisplayName = "Google-AccessToken",
options.ClientId = Configuration["google:clientid"]; ClientId = Configuration["google:clientid"],
options.ClientSecret = Configuration["google:clientsecret"]; ClientSecret = Configuration["google:clientsecret"],
options.CallbackPath = new PathString("/signin-google-token"); CallbackPath = new PathString("/signin-google-token"),
options.AuthorizationEndpoint = GoogleDefaults.AuthorizationEndpoint; AuthorizationEndpoint = GoogleDefaults.AuthorizationEndpoint,
options.TokenEndpoint = GoogleDefaults.TokenEndpoint; TokenEndpoint = GoogleDefaults.TokenEndpoint,
options.Scope.Add("openid"); Scope = { "openid", "profile", "email" },
options.Scope.Add("profile"); SaveTokensAsClaims = true
options.Scope.Add("email");
options.SaveTokensAsClaims = true;
}); });
// See config.json // See config.json
// https://console.developers.google.com/project // https://console.developers.google.com/project
app.UseGoogleAuthentication(options => app.UseGoogleAuthentication(new GoogleOptions
{ {
options.ClientId = Configuration["google:clientid"]; ClientId = Configuration["google:clientid"],
options.ClientSecret = Configuration["google:clientsecret"]; ClientSecret = Configuration["google:clientsecret"],
options.Events = new OAuthEvents() Events = new OAuthEvents()
{ {
OnRemoteFailure = ctx => OnRemoteFailure = ctx =>
@ -112,17 +109,16 @@ namespace CookieSample
ctx.HandleResponse(); ctx.HandleResponse();
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}); });
// See config.json // See config.json
// https://apps.twitter.com/ // https://apps.twitter.com/
app.UseTwitterAuthentication(options => app.UseTwitterAuthentication(new TwitterOptions
{ {
options.ConsumerKey = Configuration["twitter:consumerkey"]; ConsumerKey = Configuration["twitter:consumerkey"],
options.ConsumerSecret = Configuration["twitter:consumersecret"]; ConsumerSecret = Configuration["twitter:consumersecret"],
options.Events = new TwitterEvents() Events = new TwitterEvents()
{ {
OnRemoteFailure = ctx => OnRemoteFailure = ctx =>
{ {
@ -130,7 +126,7 @@ namespace CookieSample
ctx.HandleResponse(); ctx.HandleResponse();
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}); });
// 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.
@ -151,56 +147,56 @@ namespace CookieSample
The sample app can then be run via: The sample app can then be run via:
dnx . web dnx . web
*/ */
app.UseOAuthAuthentication(options => app.UseOAuthAuthentication(new OAuthOptions
{ {
options.AuthenticationScheme = "Microsoft-AccessToken"; AuthenticationScheme = "Microsoft-AccessToken",
options.DisplayName = "MicrosoftAccount-AccessToken - Requires project changes"; DisplayName = "MicrosoftAccount-AccessToken - Requires project changes",
options.ClientId = Configuration["msa:clientid"]; ClientId = Configuration["msa:clientid"],
options.ClientSecret = Configuration["msa:clientsecret"]; ClientSecret = Configuration["msa:clientsecret"],
options.CallbackPath = new PathString("/signin-microsoft-token"); CallbackPath = new PathString("/signin-microsoft-token"),
options.AuthorizationEndpoint = MicrosoftAccountDefaults.AuthorizationEndpoint; AuthorizationEndpoint = MicrosoftAccountDefaults.AuthorizationEndpoint,
options.TokenEndpoint = MicrosoftAccountDefaults.TokenEndpoint; TokenEndpoint = MicrosoftAccountDefaults.TokenEndpoint,
options.Scope.Add("wl.basic"); Scope = { "wl.basic" },
options.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(new MicrosoftAccountOptions
{ {
options.DisplayName = "MicrosoftAccount - Requires project changes"; DisplayName = "MicrosoftAccount - Requires project changes",
options.ClientId = Configuration["msa:clientid"]; ClientId = Configuration["msa:clientid"],
options.ClientSecret = Configuration["msa:clientsecret"]; ClientSecret = Configuration["msa:clientsecret"],
options.Scope.Add("wl.emails"); Scope = { "wl.emails" }
}); });
// See config.json // See config.json
// https://github.com/settings/applications/ // https://github.com/settings/applications/
app.UseOAuthAuthentication(options => app.UseOAuthAuthentication(new OAuthOptions
{ {
options.AuthenticationScheme = "GitHub-AccessToken"; AuthenticationScheme = "GitHub-AccessToken",
options.DisplayName = "Github-AccessToken"; DisplayName = "Github-AccessToken",
options.ClientId = Configuration["github-token:clientid"]; ClientId = Configuration["github-token:clientid"],
options.ClientSecret = Configuration["github-token:clientsecret"]; ClientSecret = Configuration["github-token:clientsecret"],
options.CallbackPath = new PathString("/signin-github-token"); CallbackPath = new PathString("/signin-github-token"),
options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize"; AuthorizationEndpoint = "https://github.com/login/oauth/authorize",
options.TokenEndpoint = "https://github.com/login/oauth/access_token"; TokenEndpoint = "https://github.com/login/oauth/access_token",
options.SaveTokensAsClaims = true; SaveTokensAsClaims = true
}); });
// See config.json // See config.json
app.UseOAuthAuthentication(options => app.UseOAuthAuthentication(new OAuthOptions
{ {
options.AuthenticationScheme = "GitHub"; AuthenticationScheme = "GitHub",
options.DisplayName = "Github"; DisplayName = "Github",
options.ClientId = Configuration["github:clientid"]; ClientId = Configuration["github:clientid"],
options.ClientSecret = Configuration["github:clientsecret"]; ClientSecret = Configuration["github:clientsecret"],
options.CallbackPath = new PathString("/signin-github"); CallbackPath = new PathString("/signin-github"),
options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize"; AuthorizationEndpoint = "https://github.com/login/oauth/authorize",
options.TokenEndpoint = "https://github.com/login/oauth/access_token"; TokenEndpoint = "https://github.com/login/oauth/access_token",
options.UserInformationEndpoint = "https://api.github.com/user"; UserInformationEndpoint = "https://api.github.com/user",
options.ClaimsIssuer = "OAuth2-Github"; ClaimsIssuer = "OAuth2-Github",
// Retrieving user information is unique to each provider. // Retrieving user information is unique to each provider.
options.Events = new OAuthEvents Events = new OAuthEvents
{ {
OnCreatingTicket = async context => OnCreatingTicket = async context =>
{ {
@ -246,7 +242,7 @@ namespace CookieSample
ClaimValueTypes.String, context.Options.ClaimsIssuer)); ClaimValueTypes.String, context.Options.ClaimsIssuer));
} }
} }
}; }
}); });
// Choose an authentication type // Choose an authentication type

View File

@ -3,6 +3,7 @@
using System; using System;
using Microsoft.AspNet.Authentication.Cookies; using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -22,31 +23,8 @@ namespace Microsoft.AspNet.Builder
{ {
throw new ArgumentNullException(nameof(app)); throw new ArgumentNullException(nameof(app));
} }
return app.UseCookieAuthentication(options => { }); return app.UseMiddleware<CookieAuthenticationMiddleware>();
}
/// <summary>
/// Adds the <see cref="CookieAuthenticationMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables cookie authentication capabilities.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <param name="configureOptions">An action delegate to configure the provided <see cref="CookieAuthenticationOptions"/>.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseCookieAuthentication(this IApplicationBuilder app, Action<CookieAuthenticationOptions> configureOptions)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var options = new CookieAuthenticationOptions();
configureOptions(options);
return app.UseMiddleware<CookieAuthenticationMiddleware>(options);
} }
/// <summary> /// <summary>
@ -66,7 +44,7 @@ namespace Microsoft.AspNet.Builder
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(options));
} }
return app.UseMiddleware<CookieAuthenticationMiddleware>(options); return app.UseMiddleware<CookieAuthenticationMiddleware>(Options.Create(options));
} }
} }
} }

View File

@ -6,6 +6,7 @@ using System;
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Features; using Microsoft.AspNet.Http.Features;

View File

@ -3,9 +3,11 @@
using System; using System;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Authentication.Cookies namespace Microsoft.AspNet.Authentication.Cookies
{ {
@ -16,34 +18,14 @@ namespace Microsoft.AspNet.Authentication.Cookies
IDataProtectionProvider dataProtectionProvider, IDataProtectionProvider dataProtectionProvider,
ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
UrlEncoder urlEncoder, UrlEncoder urlEncoder,
CookieAuthenticationOptions options) IOptions<CookieAuthenticationOptions> options)
: base(next, options, loggerFactory, urlEncoder) : base(next, options, loggerFactory, urlEncoder)
{ {
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (dataProtectionProvider == null) if (dataProtectionProvider == null)
{ {
throw new ArgumentNullException(nameof(dataProtectionProvider)); throw new ArgumentNullException(nameof(dataProtectionProvider));
} }
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
if (urlEncoder == null)
{
throw new ArgumentNullException(nameof(urlEncoder));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (Options.Events == null) if (Options.Events == null)
{ {
Options.Events = new CookieAuthenticationEvents(); Options.Events = new CookieAuthenticationEvents();

View File

@ -4,11 +4,13 @@
using System; using System;
using System.ComponentModel; using System.ComponentModel;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Authentication.Cookies namespace Microsoft.AspNet.Builder
{ {
/// <summary> /// <summary>
/// Contains the options used by the CookiesAuthenticationMiddleware /// Contains the options used by the CookiesAuthenticationMiddleware

View File

@ -2,9 +2,8 @@
// 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.Security.Claims; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;
namespace Microsoft.AspNet.Authentication.Cookies namespace Microsoft.AspNet.Authentication.Cookies
{ {

View File

@ -2,6 +2,7 @@
// 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.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;

View File

@ -2,6 +2,7 @@
// 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.Security.Claims; using System.Security.Claims;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;

View File

@ -2,6 +2,7 @@
// 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.Security.Claims; using System.Security.Claims;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;

View File

@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;

View File

@ -3,6 +3,7 @@
using System; using System;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;

View File

@ -11,6 +11,7 @@
}, },
"dependencies": { "dependencies": {
"Microsoft.AspNet.Authentication": "1.0.0-*", "Microsoft.AspNet.Authentication": "1.0.0-*",
"Microsoft.Extensions.Options": "1.0.0-*",
"Microsoft.Extensions.WebEncoders": "1.0.0-*", "Microsoft.Extensions.WebEncoders": "1.0.0-*",
"Newtonsoft.Json": "6.0.6" "Newtonsoft.Json": "6.0.6"
}, },

View File

@ -3,6 +3,7 @@
using System; using System;
using Microsoft.AspNet.Authentication.Facebook; using Microsoft.AspNet.Authentication.Facebook;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder
/// Adds the <see cref="FacebookMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Facebook authentication capabilities. /// Adds the <see cref="FacebookMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Facebook authentication capabilities.
/// </summary> /// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <param name="configureOptions">An action delegate to configure the provided <see cref="FacebookOptions"/>.</param>
/// <returns>A reference to this instance after the operation has completed.</returns> /// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseFacebookAuthentication(this IApplicationBuilder app, Action<FacebookOptions> configureOptions) public static IApplicationBuilder UseFacebookAuthentication(this IApplicationBuilder app)
{ {
if (app == null) if (app == null)
{ {
throw new ArgumentNullException(nameof(app)); throw new ArgumentNullException(nameof(app));
} }
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var options = new FacebookOptions(); return app.UseMiddleware<FacebookMiddleware>();
configureOptions(options);
return app.UseMiddleware<FacebookMiddleware>(options);
} }
/// <summary> /// <summary>
@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(options));
} }
return app.UseMiddleware<FacebookMiddleware>(options); return app.UseMiddleware<FacebookMiddleware>(Options.Create(options));
} }
} }
} }

View File

@ -8,6 +8,7 @@ using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.WebUtilities; using Microsoft.AspNet.WebUtilities;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;

View File

@ -5,6 +5,7 @@ using System;
using System.Globalization; using System.Globalization;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -33,7 +34,7 @@ namespace Microsoft.AspNet.Authentication.Facebook
ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
UrlEncoder encoder, UrlEncoder encoder,
IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<SharedAuthenticationOptions> sharedOptions,
FacebookOptions options) IOptions<FacebookOptions> options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options) : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
{ {
if (next == null) if (next == null)

View File

@ -2,10 +2,10 @@
// 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.Collections.Generic; using System.Collections.Generic;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.Facebook;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.Facebook namespace Microsoft.AspNet.Builder
{ {
/// <summary> /// <summary>
/// Configuration options for <see cref="FacebookMiddleware"/>. /// Configuration options for <see cref="FacebookMiddleware"/>.

View File

@ -3,6 +3,7 @@
using System; using System;
using Microsoft.AspNet.Authentication.Google; using Microsoft.AspNet.Authentication.Google;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder
/// Adds the <see cref="GoogleMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Google authentication capabilities. /// Adds the <see cref="GoogleMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Google authentication capabilities.
/// </summary> /// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <param name="configureOptions">An action delegate to configure the provided <see cref="GoogleOptions"/>.</param>
/// <returns>A reference to this instance after the operation has completed.</returns> /// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseGoogleAuthentication(this IApplicationBuilder app, Action<GoogleOptions> configureOptions) public static IApplicationBuilder UseGoogleAuthentication(this IApplicationBuilder app)
{ {
if (app == null) if (app == null)
{ {
throw new ArgumentNullException(nameof(app)); throw new ArgumentNullException(nameof(app));
} }
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var options = new GoogleOptions(); return app.UseMiddleware<GoogleMiddleware>();
configureOptions(options);
return app.UseMiddleware<GoogleMiddleware>(options);
} }
/// <summary> /// <summary>
@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(options));
} }
return app.UseMiddleware<GoogleMiddleware>(options); return app.UseMiddleware<GoogleMiddleware>(Options.Create(options));
} }
} }
} }

View File

@ -7,8 +7,9 @@ using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.WebUtilities; using Microsoft.AspNet.WebUtilities;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;

View File

@ -5,6 +5,7 @@ using System;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -34,7 +35,7 @@ namespace Microsoft.AspNet.Authentication.Google
ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
UrlEncoder encoder, UrlEncoder encoder,
IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<SharedAuthenticationOptions> sharedOptions,
GoogleOptions options) IOptions<GoogleOptions> options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options) : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
{ {
if (next == null) if (next == null)

View File

@ -1,10 +1,10 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.Google;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.Google namespace Microsoft.AspNet.Builder
{ {
/// <summary> /// <summary>
/// Configuration options for <see cref="GoogleMiddleware"/>. /// Configuration options for <see cref="GoogleMiddleware"/>.

View File

@ -2,6 +2,7 @@
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.JwtBearer

View File

@ -2,6 +2,7 @@
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.JwtBearer

View File

@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;

View File

@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.JwtBearer

View File

@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.JwtBearer

View File

@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.JwtBearer

View File

@ -3,6 +3,7 @@
using System; using System;
using Microsoft.AspNet.Authentication.JwtBearer; using Microsoft.AspNet.Authentication.JwtBearer;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -21,23 +22,15 @@ namespace Microsoft.AspNet.Builder
/// See also http://tools.ietf.org/html/rfc6749 /// See also http://tools.ietf.org/html/rfc6749
/// </summary> /// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <param name="configureOptions">An action delegate to configure the provided <see cref="JwtBearerOptions"/>.</param>
/// <returns>A reference to this instance after the operation has completed.</returns> /// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseJwtBearerAuthentication(this IApplicationBuilder app, Action<JwtBearerOptions> configureOptions) public static IApplicationBuilder UseJwtBearerAuthentication(this IApplicationBuilder app)
{ {
if (app == null) if (app == null)
{ {
throw new ArgumentNullException(nameof(app)); throw new ArgumentNullException(nameof(app));
} }
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var options = new JwtBearerOptions(); return app.UseMiddleware<JwtBearerMiddleware>();
configureOptions(options);
return app.UseMiddleware<JwtBearerMiddleware>(options);
} }
/// <summary> /// <summary>
@ -63,7 +56,7 @@ namespace Microsoft.AspNet.Builder
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(options));
} }
return app.UseMiddleware<JwtBearerMiddleware>(options); return app.UseMiddleware<JwtBearerMiddleware>(Options.Create(options));
} }
} }
} }

View File

@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
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;

View File

@ -4,8 +4,10 @@
using System; using System;
using System.Net.Http; using System.Net.Http;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;
@ -27,7 +29,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
RequestDelegate next, RequestDelegate next,
ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
UrlEncoder encoder, UrlEncoder encoder,
JwtBearerOptions options) IOptions<JwtBearerOptions> options)
: base(next, options, loggerFactory, encoder) : base(next, options, loggerFactory, encoder)
{ {
if (next == null) if (next == null)

View File

@ -6,11 +6,13 @@ using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Net.Http; using System.Net.Http;
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authentication.JwtBearer;
using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Builder
{ {
/// <summary> /// <summary>
/// Options class provides information needed to control Bearer Authentication middleware behavior /// Options class provides information needed to control Bearer Authentication middleware behavior

View File

@ -3,6 +3,7 @@
using System; using System;
using Microsoft.AspNet.Authentication.MicrosoftAccount; using Microsoft.AspNet.Authentication.MicrosoftAccount;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder
/// Adds the <see cref="MicrosoftAccountMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Microsoft Account authentication capabilities. /// Adds the <see cref="MicrosoftAccountMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Microsoft Account authentication capabilities.
/// </summary> /// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <param name="configureOptions">An action delegate to configure the provided <see cref="MicrosoftAccountOptions"/>.</param>
/// <returns>A reference to this instance after the operation has completed.</returns> /// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseMicrosoftAccountAuthentication(this IApplicationBuilder app, Action<MicrosoftAccountOptions> configureOptions) public static IApplicationBuilder UseMicrosoftAccountAuthentication(this IApplicationBuilder app)
{ {
if (app == null) if (app == null)
{ {
throw new ArgumentNullException(nameof(app)); throw new ArgumentNullException(nameof(app));
} }
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var options = new MicrosoftAccountOptions(); return app.UseMiddleware<MicrosoftAccountMiddleware>();
configureOptions(options);
return app.UseMiddleware<MicrosoftAccountMiddleware>(options);
} }
/// <summary> /// <summary>
@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(options));
} }
return app.UseMiddleware<MicrosoftAccountMiddleware>(options); return app.UseMiddleware<MicrosoftAccountMiddleware>(Options.Create(options));
} }
} }
} }

View File

@ -6,6 +6,7 @@ using System.Net.Http.Headers;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;

View File

@ -4,6 +4,7 @@
using System; using System;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -32,7 +33,7 @@ namespace Microsoft.AspNet.Authentication.MicrosoftAccount
ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
UrlEncoder encoder, UrlEncoder encoder,
IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<SharedAuthenticationOptions> sharedOptions,
MicrosoftAccountOptions options) IOptions<MicrosoftAccountOptions> options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options) : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
{ {
if (next == null) if (next == null)

View File

@ -2,9 +2,9 @@
// 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 Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.MicrosoftAccount;
namespace Microsoft.AspNet.Authentication.MicrosoftAccount namespace Microsoft.AspNet.Builder
{ {
/// <summary> /// <summary>
/// Configuration options for <see cref="MicrosoftAccountMiddleware"/>. /// Configuration options for <see cref="MicrosoftAccountMiddleware"/>.

View File

@ -5,8 +5,8 @@ using System;
using System.Globalization; using System.Globalization;
using System.Net.Http; using System.Net.Http;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
namespace Microsoft.AspNet.Authentication.OAuth namespace Microsoft.AspNet.Authentication.OAuth

View File

@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;

View File

@ -3,6 +3,7 @@
using System; using System;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder
/// Adds the <see cref="OAuthMiddleware{TOptions}"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables OAuth 2.0 authentication capabilities. /// Adds the <see cref="OAuthMiddleware{TOptions}"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables OAuth 2.0 authentication capabilities.
/// </summary> /// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <param name="configureOptions">An action delegate to configure the provided <see cref="OAuthOptions"/>.</param>
/// <returns>A reference to this instance after the operation has completed.</returns> /// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseOAuthAuthentication(this IApplicationBuilder app, Action<OAuthOptions> configureOptions) public static IApplicationBuilder UseOAuthAuthentication(this IApplicationBuilder app)
{ {
if (app == null) if (app == null)
{ {
throw new ArgumentNullException(nameof(app)); throw new ArgumentNullException(nameof(app));
} }
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var options = new OAuthOptions(); return app.UseMiddleware<OAuthMiddleware<OAuthOptions>>();
configureOptions(options);
return app.UseMiddleware<OAuthMiddleware<OAuthOptions>>(options);
} }
/// <summary> /// <summary>
@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(options));
} }
return app.UseMiddleware<OAuthMiddleware<OAuthOptions>>(options); return app.UseMiddleware<OAuthMiddleware<OAuthOptions>>(Options.Create(options));
} }
} }
} }

View File

@ -9,6 +9,7 @@ using System.Security.Claims;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Extensions; using Microsoft.AspNet.Http.Extensions;

View File

@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Net.Http; using System.Net.Http;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -32,7 +33,7 @@ namespace Microsoft.AspNet.Authentication.OAuth
ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
UrlEncoder encoder, UrlEncoder encoder,
IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<SharedAuthenticationOptions> sharedOptions,
TOptions options) IOptions<TOptions> options)
: base(next, options, loggerFactory, encoder) : base(next, options, loggerFactory, encoder)
{ {
if (next == null) if (next == null)

View File

@ -2,9 +2,11 @@
// 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.Collections.Generic; using System.Collections.Generic;
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
namespace Microsoft.AspNet.Authentication.OAuth namespace Microsoft.AspNet.Builder
{ {
/// <summary> /// <summary>
/// Configuration options for <see cref="OAuthMiddleware"/>. /// Configuration options for <see cref="OAuthMiddleware"/>.

View File

@ -2,8 +2,8 @@
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Microsoft.AspNet.Authentication.OpenIdConnect namespace Microsoft.AspNet.Authentication.OpenIdConnect
{ {

View File

@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;

View File

@ -3,6 +3,7 @@
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;

View File

@ -1,9 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Microsoft.AspNet.Authentication.OpenIdConnect namespace Microsoft.AspNet.Authentication.OpenIdConnect
{ {

View File

@ -2,6 +2,7 @@
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;

View File

@ -1,8 +1,8 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Microsoft.AspNet.Authentication.OpenIdConnect namespace Microsoft.AspNet.Authentication.OpenIdConnect
{ {

View File

@ -1,9 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Microsoft.AspNet.Authentication.OpenIdConnect namespace Microsoft.AspNet.Authentication.OpenIdConnect
{ {

View File

@ -1,4 +1,8 @@
using Microsoft.AspNet.Http; // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;

View File

@ -1,8 +1,8 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
namespace Microsoft.AspNet.Authentication.OpenIdConnect namespace Microsoft.AspNet.Authentication.OpenIdConnect

View File

@ -3,6 +3,7 @@
using System; using System;
using Microsoft.AspNet.Authentication.OpenIdConnect; using Microsoft.AspNet.Authentication.OpenIdConnect;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder
/// Adds the <see cref="OpenIdConnectMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables OpenID Connect authentication capabilities. /// Adds the <see cref="OpenIdConnectMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables OpenID Connect authentication capabilities.
/// </summary> /// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <param name="configureOptions">An action delegate to configure the provided <see cref="OpenIdConnectOptions"/>.</param>
/// <returns>A reference to this instance after the operation has completed.</returns> /// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseOpenIdConnectAuthentication(this IApplicationBuilder app, Action<OpenIdConnectOptions> configureOptions) public static IApplicationBuilder UseOpenIdConnectAuthentication(this IApplicationBuilder app)
{ {
if (app == null) if (app == null)
{ {
throw new ArgumentNullException(nameof(app)); throw new ArgumentNullException(nameof(app));
} }
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var options = new OpenIdConnectOptions(); return app.UseMiddleware<OpenIdConnectMiddleware>();
configureOptions(options);
return app.UseMiddleware<OpenIdConnectMiddleware>(options);
} }
/// <summary> /// <summary>
@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(options));
} }
return app.UseMiddleware<OpenIdConnectMiddleware>(options); return app.UseMiddleware<OpenIdConnectMiddleware>(Options.Create(options));
} }
} }
} }

View File

@ -13,6 +13,7 @@ using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
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;

View File

@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -38,7 +39,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
UrlEncoder encoder, UrlEncoder encoder,
IServiceProvider services, IServiceProvider services,
IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<SharedAuthenticationOptions> sharedOptions,
OpenIdConnectOptions options, IOptions<OpenIdConnectOptions> options,
HtmlEncoder htmlEncoder) HtmlEncoder htmlEncoder)
: base(next, options, loggerFactory, encoder) : base(next, options, loggerFactory, encoder)
{ {

View File

@ -5,13 +5,15 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authentication.OpenIdConnect;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
namespace Microsoft.AspNet.Authentication.OpenIdConnect namespace Microsoft.AspNet.Builder
{ {
/// <summary> /// <summary>
/// Configuration options for <see cref="OpenIdConnectOptions"/> /// Configuration options for <see cref="OpenIdConnectOptions"/>

View File

@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.Twitter namespace Microsoft.AspNet.Authentication.Twitter

View File

@ -2,6 +2,7 @@
// 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.Security.Claims; using System.Security.Claims;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;

View File

@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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 Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;

View File

@ -3,6 +3,7 @@
using System; using System;
using Microsoft.AspNet.Authentication.Twitter; using Microsoft.AspNet.Authentication.Twitter;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder
/// Adds the <see cref="TwitterMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Twitter authentication capabilities. /// Adds the <see cref="TwitterMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Twitter authentication capabilities.
/// </summary> /// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <param name="configureOptions">An action delegate to configure the provided <see cref="TwitterOptions"/>.</param>
/// <returns>A reference to this instance after the operation has completed.</returns> /// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseTwitterAuthentication(this IApplicationBuilder app, Action<TwitterOptions> configureOptions) public static IApplicationBuilder UseTwitterAuthentication(this IApplicationBuilder app)
{ {
if (app == null) if (app == null)
{ {
throw new ArgumentNullException(nameof(app)); throw new ArgumentNullException(nameof(app));
} }
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var options = new TwitterOptions(); return app.UseMiddleware<TwitterMiddleware>();
configureOptions(options);
return app.UseMiddleware<TwitterMiddleware>(options);
} }
/// <summary> /// <summary>
@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(options));
} }
return app.UseMiddleware<TwitterMiddleware>(options); return app.UseMiddleware<TwitterMiddleware>(Options.Create(options));
} }
} }
} }

View File

@ -9,6 +9,7 @@ using System.Security.Claims;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
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;

View File

@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Net.Http; using System.Net.Http;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -37,7 +38,7 @@ namespace Microsoft.AspNet.Authentication.Twitter
ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
UrlEncoder encoder, UrlEncoder encoder,
IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<SharedAuthenticationOptions> sharedOptions,
TwitterOptions options) IOptions<TwitterOptions> options)
: base(next, options, loggerFactory, encoder) : base(next, options, loggerFactory, encoder)
{ {
if (next == null) if (next == null)

View File

@ -2,10 +2,11 @@
// 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.Net.Http; using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authentication.Twitter;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.Twitter namespace Microsoft.AspNet.Builder
{ {
/// <summary> /// <summary>
/// Options for the Twitter authentication middleware. /// Options for the Twitter authentication middleware.

View File

@ -4,6 +4,7 @@
using System; using System;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
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;

View File

@ -4,8 +4,10 @@
using System; using System;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Authentication namespace Microsoft.AspNet.Authentication
{ {
@ -15,7 +17,7 @@ namespace Microsoft.AspNet.Authentication
protected AuthenticationMiddleware( protected AuthenticationMiddleware(
RequestDelegate next, RequestDelegate next,
TOptions options, IOptions<TOptions> options,
ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
UrlEncoder encoder) UrlEncoder encoder)
{ {
@ -39,7 +41,7 @@ namespace Microsoft.AspNet.Authentication
throw new ArgumentNullException(nameof(encoder)); throw new ArgumentNullException(nameof(encoder));
} }
Options = options; Options = options.Value;
Logger = loggerFactory.CreateLogger(this.GetType().FullName); Logger = loggerFactory.CreateLogger(this.GetType().FullName);
UrlEncoder = encoder; UrlEncoder = encoder;

View File

@ -3,7 +3,7 @@
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
namespace Microsoft.AspNet.Authentication namespace Microsoft.AspNet.Builder
{ {
/// <summary> /// <summary>
/// Base Options for all authentication middleware /// Base Options for all authentication middleware

View File

@ -5,6 +5,7 @@ using System;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Authentication; using Microsoft.AspNet.Authentication;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -13,6 +14,21 @@ namespace Microsoft.AspNet.Builder
/// </summary> /// </summary>
public static class ClaimsTransformationAppBuilderExtensions public static class ClaimsTransformationAppBuilderExtensions
{ {
/// <summary>
/// Adds the <see cref="ClaimsTransformationMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables claims transformation capabilities.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseClaimsTransformation(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseMiddleware<ClaimsTransformationMiddleware>();
}
/// <summary> /// <summary>
/// Adds the <see cref="ClaimsTransformationMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables claims transformation capabilities. /// Adds the <see cref="ClaimsTransformationMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables claims transformation capabilities.
/// </summary> /// </summary>
@ -30,35 +46,12 @@ namespace Microsoft.AspNet.Builder
throw new ArgumentNullException(nameof(transform)); throw new ArgumentNullException(nameof(transform));
} }
return app.UseClaimsTransformation(options => return app.UseClaimsTransformation(new ClaimsTransformationOptions
{ {
options.Transformer = new ClaimsTransformer { OnTransform = transform }; Transformer = new ClaimsTransformer { OnTransform = transform }
}); });
} }
/// <summary>
/// Adds the <see cref="ClaimsTransformationMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables claims transformation capabilities.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <param name="configureOptions">An action delegate to configure the provided <see cref="ClaimsTransformationOptions"/>.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseClaimsTransformation(this IApplicationBuilder app, Action<ClaimsTransformationOptions> configureOptions)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var options = new ClaimsTransformationOptions();
configureOptions(options);
return app.UseMiddleware<ClaimsTransformationMiddleware>(options);
}
/// <summary> /// <summary>
/// Adds the <see cref="ClaimsTransformationMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables claims transformation capabilities. /// Adds the <see cref="ClaimsTransformationMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables claims transformation capabilities.
/// </summary> /// </summary>
@ -76,7 +69,7 @@ namespace Microsoft.AspNet.Builder
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(options));
} }
return app.UseMiddleware<ClaimsTransformationMiddleware>(options); return app.UseMiddleware<ClaimsTransformationMiddleware>(Options.Create(options));
} }
} }
} }

View File

@ -3,7 +3,9 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Authentication namespace Microsoft.AspNet.Authentication
{ {
@ -13,7 +15,7 @@ namespace Microsoft.AspNet.Authentication
public ClaimsTransformationMiddleware( public ClaimsTransformationMiddleware(
RequestDelegate next, RequestDelegate next,
ClaimsTransformationOptions options) IOptions<ClaimsTransformationOptions> options)
{ {
if (next == null) if (next == null)
{ {
@ -25,7 +27,7 @@ namespace Microsoft.AspNet.Authentication
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(options));
} }
Options = options; Options = options.Value;
_next = next; _next = next;
} }

View File

@ -1,7 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// 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.
namespace Microsoft.AspNet.Authentication using Microsoft.AspNet.Authentication;
namespace Microsoft.AspNet.Builder
{ {
public class ClaimsTransformationOptions public class ClaimsTransformationOptions
{ {

View File

@ -2,6 +2,7 @@
// 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.Security.Claims; using System.Security.Claims;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;

View File

@ -3,6 +3,7 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http.Features.Authentication; using Microsoft.AspNet.Http.Features.Authentication;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;

View File

@ -3,10 +3,10 @@
using System; using System;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Authentication;
namespace Microsoft.AspNet.Authentication namespace Microsoft.AspNet.Builder
{ {
public class RemoteAuthenticationOptions : AuthenticationOptions public class RemoteAuthenticationOptions : AuthenticationOptions
{ {

View File

@ -24,8 +24,7 @@ namespace Microsoft.Extensions.DependencyInjection
{ {
throw new ArgumentNullException(nameof(services)); throw new ArgumentNullException(nameof(services));
} }
services.AddOptions();
services.TryAdd(ServiceDescriptor.Transient<IAuthorizationService, DefaultAuthorizationService>()); services.TryAdd(ServiceDescriptor.Transient<IAuthorizationService, DefaultAuthorizationService>());
services.TryAddEnumerable(ServiceDescriptor.Transient<IAuthorizationHandler, PassThroughAuthorizationHandler>()); services.TryAddEnumerable(ServiceDescriptor.Transient<IAuthorizationHandler, PassThroughAuthorizationHandler>());
return services; return services;

View File

@ -3,6 +3,7 @@
using System; using System;
using Microsoft.AspNet.CookiePolicy; using Microsoft.AspNet.CookiePolicy;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder
/// Adds the <see cref="CookiePolicyMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables cookie policy capabilities. /// Adds the <see cref="CookiePolicyMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables cookie policy capabilities.
/// </summary> /// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <param name="configureOptions">An action delegate to configure the provided <see cref="CookiePolicyOptions"/>.</param>
/// <returns>A reference to this instance after the operation has completed.</returns> /// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseCookiePolicy(this IApplicationBuilder app, Action<CookiePolicyOptions> configureOptions) public static IApplicationBuilder UseCookiePolicy(this IApplicationBuilder app)
{ {
if (app == null) if (app == null)
{ {
throw new ArgumentNullException(nameof(app)); throw new ArgumentNullException(nameof(app));
} }
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var options = new CookiePolicyOptions(); return app.UseMiddleware<CookiePolicyMiddleware>();
configureOptions(options);
return app.UseMiddleware<CookiePolicyMiddleware>(options);
} }
/// <summary> /// <summary>
@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(options));
} }
return app.UseMiddleware<CookiePolicyMiddleware>(options); return app.UseMiddleware<CookiePolicyMiddleware>(Options.Create(options));
} }
} }
} }

View File

@ -3,9 +3,10 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Http.Features.Internal; using Microsoft.AspNet.Http.Features.Internal;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNet.CookiePolicy namespace Microsoft.AspNet.CookiePolicy
{ {
@ -15,9 +16,9 @@ namespace Microsoft.AspNet.CookiePolicy
public CookiePolicyMiddleware( public CookiePolicyMiddleware(
RequestDelegate next, RequestDelegate next,
CookiePolicyOptions options) IOptions<CookiePolicyOptions> options)
{ {
Options = options; Options = options.Value;
_next = next; _next = next;
} }

View File

@ -2,8 +2,9 @@
// 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 Microsoft.AspNet.CookiePolicy;
namespace Microsoft.AspNet.CookiePolicy namespace Microsoft.AspNet.Builder
{ {
public class CookiePolicyOptions public class CookiePolicyOptions
{ {

View File

@ -10,7 +10,8 @@
"keyFile": "../../tools/Key.snk" "keyFile": "../../tools/Key.snk"
}, },
"dependencies": { "dependencies": {
"Microsoft.AspNet.Http": "1.0.0-*" "Microsoft.AspNet.Http": "1.0.0-*",
"Microsoft.Extensions.Options": "1.0.0-*"
}, },
"frameworks": { "frameworks": {
"net451": {}, "net451": {},

View File

@ -6,6 +6,7 @@ using System.IO;
using System.Security.Claims; using System.Security.Claims;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Features; using Microsoft.AspNet.Http.Features;

View File

@ -27,9 +27,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task NormalRequestPassesThrough() public async Task NormalRequestPassesThrough()
{ {
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions());
{
});
var response = await server.CreateClient().GetAsync("http://example.com/normal"); var response = await server.CreateClient().GetAsync("http://example.com/normal");
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
} }
@ -37,10 +35,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task AjaxLoginRedirectToReturnUrlTurnsInto200WithLocationHeader() public async Task AjaxLoginRedirectToReturnUrlTurnsInto200WithLocationHeader()
{ {
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.AutomaticChallenge = true; AutomaticChallenge = true,
options.LoginPath = "/login"; LoginPath = "/login"
}); });
var transaction = await SendAsync(server, "http://example.com/protected?X-Requested-With=XMLHttpRequest"); var transaction = await SendAsync(server, "http://example.com/protected?X-Requested-With=XMLHttpRequest");
@ -53,9 +51,9 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task AjaxForbidTurnsInto403WithLocationHeader() public async Task AjaxForbidTurnsInto403WithLocationHeader()
{ {
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.AccessDeniedPath = "/denied"; AccessDeniedPath = "/denied"
}); });
var transaction = await SendAsync(server, "http://example.com/forbid?X-Requested-With=XMLHttpRequest"); var transaction = await SendAsync(server, "http://example.com/forbid?X-Requested-With=XMLHttpRequest");
@ -68,9 +66,9 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task AjaxLogoutRedirectToReturnUrlTurnsInto200WithLocationHeader() public async Task AjaxLogoutRedirectToReturnUrlTurnsInto200WithLocationHeader()
{ {
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.LogoutPath = "/signout"; LogoutPath = "/signout"
}); });
var transaction = await SendAsync(server, "http://example.com/signout?X-Requested-With=XMLHttpRequest&ReturnUrl=/"); var transaction = await SendAsync(server, "http://example.com/signout?X-Requested-With=XMLHttpRequest&ReturnUrl=/");
@ -83,9 +81,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task AjaxChallengeRedirectTurnsInto200WithLocationHeader() public async Task AjaxChallengeRedirectTurnsInto200WithLocationHeader()
{ {
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions());
{
});
var transaction = await SendAsync(server, "http://example.com/challenge?X-Requested-With=XMLHttpRequest&ReturnUrl=/"); var transaction = await SendAsync(server, "http://example.com/challenge?X-Requested-With=XMLHttpRequest&ReturnUrl=/");
Assert.Equal(HttpStatusCode.Unauthorized, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Unauthorized, transaction.Response.StatusCode);
@ -100,10 +96,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
[InlineData(false)] [InlineData(false)]
public async Task ProtectedRequestShouldRedirectToLoginOnlyWhenAutomatic(bool auto) public async Task ProtectedRequestShouldRedirectToLoginOnlyWhenAutomatic(bool auto)
{ {
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.LoginPath = new PathString("/login"); LoginPath = new PathString("/login"),
options.AutomaticChallenge = auto; AutomaticChallenge = auto
}); });
var transaction = await SendAsync(server, "http://example.com/protected"); var transaction = await SendAsync(server, "http://example.com/protected");
@ -120,7 +116,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task ProtectedCustomRequestShouldRedirectToCustomRedirectUri() public async Task ProtectedCustomRequestShouldRedirectToCustomRedirectUri()
{ {
var server = CreateServer(options => options.AutomaticChallenge = true); var server = CreateServer(new CookieAuthenticationOptions
{
AutomaticChallenge = true
});
var transaction = await SendAsync(server, "http://example.com/protected/CustomRedirect"); var transaction = await SendAsync(server, "http://example.com/protected/CustomRedirect");
@ -151,10 +150,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task SignInCausesDefaultCookieToBeCreated() public async Task SignInCausesDefaultCookieToBeCreated()
{ {
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.LoginPath = new PathString("/login"); LoginPath = new PathString("/login"),
options.CookieName = "TestCookie"; CookieName = "TestCookie"
}, SignInAsAlice); }, SignInAsAlice);
var transaction = await SendAsync(server, "http://example.com/testpath"); var transaction = await SendAsync(server, "http://example.com/testpath");
@ -171,10 +170,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task SignInWrongAuthTypeThrows() public async Task SignInWrongAuthTypeThrows()
{ {
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.LoginPath = new PathString("/login"); LoginPath = new PathString("/login"),
options.CookieName = "TestCookie"; CookieName = "TestCookie"
}, SignInAsWrong); }, SignInAsWrong);
await Assert.ThrowsAsync<InvalidOperationException>(async () => await SendAsync(server, "http://example.com/testpath")); await Assert.ThrowsAsync<InvalidOperationException>(async () => await SendAsync(server, "http://example.com/testpath"));
@ -183,10 +182,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task SignOutWrongAuthTypeThrows() public async Task SignOutWrongAuthTypeThrows()
{ {
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.LoginPath = new PathString("/login"); LoginPath = new PathString("/login"),
options.CookieName = "TestCookie"; CookieName = "TestCookie"
}, SignOutAsWrong); }, SignOutAsWrong);
await Assert.ThrowsAsync<InvalidOperationException>(async () => await SendAsync(server, "http://example.com/testpath")); await Assert.ThrowsAsync<InvalidOperationException>(async () => await SendAsync(server, "http://example.com/testpath"));
@ -204,11 +203,11 @@ namespace Microsoft.AspNet.Authentication.Cookies
string requestUri, string requestUri,
bool shouldBeSecureOnly) bool shouldBeSecureOnly)
{ {
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.LoginPath = new PathString("/login"); LoginPath = new PathString("/login"),
options.CookieName = "TestCookie"; CookieName = "TestCookie",
options.CookieSecure = cookieSecureOption; CookieSecure = cookieSecureOption
}, SignInAsAlice); }, SignInAsAlice);
var transaction = await SendAsync(server, requestUri); var transaction = await SendAsync(server, requestUri);
@ -227,13 +226,13 @@ namespace Microsoft.AspNet.Authentication.Cookies
[Fact] [Fact]
public async Task CookieOptionsAlterSetCookieHeader() public async Task CookieOptionsAlterSetCookieHeader()
{ {
TestServer server1 = CreateServer(options => TestServer server1 = CreateServer(new CookieAuthenticationOptions
{ {
options.CookieName = "TestCookie"; CookieName = "TestCookie",
options.CookiePath = "/foo"; CookiePath = "/foo",
options.CookieDomain = "another.com"; CookieDomain = "another.com",
options.CookieSecure = CookieSecureOption.Always; CookieSecure = CookieSecureOption.Always,
options.CookieHttpOnly = true; CookieHttpOnly = true
}, SignInAsAlice, new Uri("http://example.com/base")); }, SignInAsAlice, new Uri("http://example.com/base"));
var transaction1 = await SendAsync(server1, "http://example.com/base/testpath"); var transaction1 = await SendAsync(server1, "http://example.com/base/testpath");
@ -246,11 +245,11 @@ namespace Microsoft.AspNet.Authentication.Cookies
Assert.Contains(" secure", setCookie1); Assert.Contains(" secure", setCookie1);
Assert.Contains(" httponly", setCookie1); Assert.Contains(" httponly", setCookie1);
var server2 = CreateServer(options => var server2 = CreateServer(new CookieAuthenticationOptions
{ {
options.CookieName = "SecondCookie"; CookieName = "SecondCookie",
options.CookieSecure = CookieSecureOption.Never; CookieSecure = CookieSecureOption.Never,
options.CookieHttpOnly = false; CookieHttpOnly = false
}, SignInAsAlice, new Uri("http://example.com/base")); }, SignInAsAlice, new Uri("http://example.com/base"));
var transaction2 = await SendAsync(server2, "http://example.com/base/testpath"); var transaction2 = await SendAsync(server2, "http://example.com/base/testpath");
@ -268,9 +267,9 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieContainsIdentity() public async Task CookieContainsIdentity()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock
}, SignInAsAlice); }, SignInAsAlice);
var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction1 = await SendAsync(server, "http://example.com/testpath");
@ -284,24 +283,27 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieAppliesClaimsTransform() public async Task CookieAppliesClaimsTransform()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock
}, },
SignInAsAlice, SignInAsAlice,
baseAddress: null, baseAddress: null,
claimsTransform: o => o.Transformer = new ClaimsTransformer claimsTransform: new ClaimsTransformationOptions
{ {
OnTransform = p => Transformer = new ClaimsTransformer
{ {
if (!p.Identities.Any(i => i.AuthenticationType == "xform")) OnTransform = p =>
{ {
// REVIEW: Xform runs twice, once on Authenticate, and then once from the middleware if (!p.Identities.Any(i => i.AuthenticationType == "xform"))
var id = new ClaimsIdentity("xform"); {
id.AddClaim(new Claim("xform", "yup")); // REVIEW: Xform runs twice, once on Authenticate, and then once from the middleware
p.AddIdentity(id); var id = new ClaimsIdentity("xform");
id.AddClaim(new Claim("xform", "yup"));
p.AddIdentity(id);
}
return Task.FromResult(p);
} }
return Task.FromResult(p);
} }
}); });
@ -318,11 +320,11 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieStopsWorkingAfterExpiration() public async Task CookieStopsWorkingAfterExpiration()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock,
options.ExpireTimeSpan = TimeSpan.FromMinutes(10); ExpireTimeSpan = TimeSpan.FromMinutes(10),
options.SlidingExpiration = false; SlidingExpiration = false
}, SignInAsAlice); }, SignInAsAlice);
var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction1 = await SendAsync(server, "http://example.com/testpath");
@ -349,11 +351,11 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieExpirationCanBeOverridenInSignin() public async Task CookieExpirationCanBeOverridenInSignin()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock,
options.ExpireTimeSpan = TimeSpan.FromMinutes(10); ExpireTimeSpan = TimeSpan.FromMinutes(10),
options.SlidingExpiration = false; SlidingExpiration = false
}, },
context => context =>
context.Authentication.SignInAsync("Cookies", context.Authentication.SignInAsync("Cookies",
@ -384,18 +386,18 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task ExpiredCookieWithValidatorStillExpired() public async Task ExpiredCookieWithValidatorStillExpired()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock,
options.ExpireTimeSpan = TimeSpan.FromMinutes(10); ExpireTimeSpan = TimeSpan.FromMinutes(10),
options.Events = new CookieAuthenticationEvents Events = new CookieAuthenticationEvents
{ {
OnValidatePrincipal = ctx => OnValidatePrincipal = ctx =>
{ {
ctx.ShouldRenew = true; ctx.ShouldRenew = true;
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}, },
context => context =>
context.Authentication.SignInAsync("Cookies", context.Authentication.SignInAsync("Cookies",
@ -414,12 +416,12 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieCanBeRejectedAndSignedOutByValidator() public async Task CookieCanBeRejectedAndSignedOutByValidator()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock,
options.ExpireTimeSpan = TimeSpan.FromMinutes(10); ExpireTimeSpan = TimeSpan.FromMinutes(10),
options.SlidingExpiration = false; SlidingExpiration = false,
options.Events = new CookieAuthenticationEvents Events = new CookieAuthenticationEvents
{ {
OnValidatePrincipal = ctx => OnValidatePrincipal = ctx =>
{ {
@ -427,7 +429,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
ctx.HttpContext.Authentication.SignOutAsync("Cookies"); ctx.HttpContext.Authentication.SignOutAsync("Cookies");
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}, },
context => context =>
context.Authentication.SignInAsync("Cookies", context.Authentication.SignInAsync("Cookies",
@ -444,19 +446,19 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieCanBeRenewedByValidator() public async Task CookieCanBeRenewedByValidator()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock,
options.ExpireTimeSpan = TimeSpan.FromMinutes(10); ExpireTimeSpan = TimeSpan.FromMinutes(10),
options.SlidingExpiration = false; SlidingExpiration = false,
options.Events = new CookieAuthenticationEvents Events = new CookieAuthenticationEvents
{ {
OnValidatePrincipal = ctx => OnValidatePrincipal = ctx =>
{ {
ctx.ShouldRenew = true; ctx.ShouldRenew = true;
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}, },
context => context =>
context.Authentication.SignInAsync("Cookies", context.Authentication.SignInAsync("Cookies",
@ -491,18 +493,18 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieCanBeRenewedByValidatorWithSlidingExpiry() public async Task CookieCanBeRenewedByValidatorWithSlidingExpiry()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock,
options.ExpireTimeSpan = TimeSpan.FromMinutes(10); ExpireTimeSpan = TimeSpan.FromMinutes(10),
options.Events = new CookieAuthenticationEvents Events = new CookieAuthenticationEvents
{ {
OnValidatePrincipal = ctx => OnValidatePrincipal = ctx =>
{ {
ctx.ShouldRenew = true; ctx.ShouldRenew = true;
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}, },
context => context =>
context.Authentication.SignInAsync("Cookies", context.Authentication.SignInAsync("Cookies",
@ -537,19 +539,19 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieValidatorOnlyCalledOnce() public async Task CookieValidatorOnlyCalledOnce()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock,
options.ExpireTimeSpan = TimeSpan.FromMinutes(10); ExpireTimeSpan = TimeSpan.FromMinutes(10),
options.SlidingExpiration = false; SlidingExpiration = false,
options.Events = new CookieAuthenticationEvents Events = new CookieAuthenticationEvents
{ {
OnValidatePrincipal = ctx => OnValidatePrincipal = ctx =>
{ {
ctx.ShouldRenew = true; ctx.ShouldRenew = true;
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}, },
context => context =>
context.Authentication.SignInAsync("Cookies", context.Authentication.SignInAsync("Cookies",
@ -588,12 +590,12 @@ namespace Microsoft.AspNet.Authentication.Cookies
var clock = new TestClock(); var clock = new TestClock();
DateTimeOffset? lastValidateIssuedDate = null; DateTimeOffset? lastValidateIssuedDate = null;
DateTimeOffset? lastExpiresDate = null; DateTimeOffset? lastExpiresDate = null;
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock,
options.ExpireTimeSpan = TimeSpan.FromMinutes(10); ExpireTimeSpan = TimeSpan.FromMinutes(10),
options.SlidingExpiration = sliding; SlidingExpiration = sliding,
options.Events = new CookieAuthenticationEvents Events = new CookieAuthenticationEvents
{ {
OnValidatePrincipal = ctx => OnValidatePrincipal = ctx =>
{ {
@ -602,7 +604,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
ctx.ShouldRenew = true; ctx.ShouldRenew = true;
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}, },
context => context =>
context.Authentication.SignInAsync("Cookies", context.Authentication.SignInAsync("Cookies",
@ -640,19 +642,19 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieExpirationCanBeOverridenInEvent() public async Task CookieExpirationCanBeOverridenInEvent()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock,
options.ExpireTimeSpan = TimeSpan.FromMinutes(10); ExpireTimeSpan = TimeSpan.FromMinutes(10),
options.SlidingExpiration = false; SlidingExpiration = false,
options.Events = new CookieAuthenticationEvents() Events = new CookieAuthenticationEvents()
{ {
OnSigningIn = context => OnSigningIn = context =>
{ {
context.Properties.ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5)); context.Properties.ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5));
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}, SignInAsAlice); }, SignInAsAlice);
var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction1 = await SendAsync(server, "http://example.com/testpath");
@ -678,11 +680,11 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieIsRenewedWithSlidingExpiration() public async Task CookieIsRenewedWithSlidingExpiration()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock,
options.ExpireTimeSpan = TimeSpan.FromMinutes(10); ExpireTimeSpan = TimeSpan.FromMinutes(10),
options.SlidingExpiration = true; SlidingExpiration = true
}, SignInAsAlice); }, SignInAsAlice);
var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction1 = await SendAsync(server, "http://example.com/testpath");
@ -715,7 +717,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieUsesPathBaseByDefault() public async Task CookieUsesPathBaseByDefault()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => { }, var server = CreateServer(new CookieAuthenticationOptions(),
context => context =>
{ {
Assert.Equal(new PathString("/base"), context.Request.PathBase); Assert.Equal(new PathString("/base"), context.Request.PathBase);
@ -734,10 +736,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieTurnsChallengeIntoForbidWithCookie(bool automatic) public async Task CookieTurnsChallengeIntoForbidWithCookie(bool automatic)
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.AutomaticAuthenticate = automatic; AutomaticAuthenticate = automatic,
options.SystemClock = clock; SystemClock = clock
}, },
SignInAsAlice); SignInAsAlice);
@ -758,10 +760,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieChallengeRedirectsToLoginWithoutCookie(bool automatic) public async Task CookieChallengeRedirectsToLoginWithoutCookie(bool automatic)
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.AutomaticAuthenticate = automatic; AutomaticAuthenticate = automatic,
options.SystemClock = clock; SystemClock = clock
}, },
SignInAsAlice); SignInAsAlice);
@ -779,10 +781,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieForbidRedirectsWithoutCookie(bool automatic) public async Task CookieForbidRedirectsWithoutCookie(bool automatic)
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.AutomaticAuthenticate = automatic; AutomaticAuthenticate = automatic,
options.SystemClock = clock; SystemClock = clock
}, },
SignInAsAlice); SignInAsAlice);
@ -798,10 +800,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieTurns401ToAccessDeniedWhenSetWithCookie() public async Task CookieTurns401ToAccessDeniedWhenSetWithCookie()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock,
options.AccessDeniedPath = new PathString("/accessdenied"); AccessDeniedPath = new PathString("/accessdenied")
}, },
SignInAsAlice); SignInAsAlice);
@ -819,10 +821,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieChallengeRedirectsWithLoginPath() public async Task CookieChallengeRedirectsWithLoginPath()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock,
options.LoginPath = new PathString("/page"); LoginPath = new PathString("/page")
}); });
var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction1 = await SendAsync(server, "http://example.com/testpath");
@ -836,10 +838,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
public async Task CookieChallengeWithUnauthorizedRedirectsToLoginIfNotAuthenticated() public async Task CookieChallengeWithUnauthorizedRedirectsToLoginIfNotAuthenticated()
{ {
var clock = new TestClock(); var clock = new TestClock();
var server = CreateServer(options => var server = CreateServer(new CookieAuthenticationOptions
{ {
options.SystemClock = clock; SystemClock = clock,
options.LoginPath = new PathString("/page"); LoginPath = new PathString("/page")
}); });
var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction1 = await SendAsync(server, "http://example.com/testpath");
@ -855,7 +857,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => options.LoginPath = new PathString("/page")); app.UseCookieAuthentication(new CookieAuthenticationOptions
{
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 = "/" })));
}) })
.ConfigureServices(services => services.AddAuthentication()); .ConfigureServices(services => services.AddAuthentication());
@ -895,7 +900,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => options.CookieName = "One"); app.UseCookieAuthentication(new CookieAuthenticationOptions
{
CookieName = "One"
});
app.UseCookieAuthentication(); app.UseCookieAuthentication();
app.Run(context => context.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity()))); app.Run(context => context.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity())));
}) })
@ -914,7 +922,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => options.LoginPath = new PathString("/login")); app.UseCookieAuthentication(new CookieAuthenticationOptions
{
LoginPath = new PathString("/login")
});
app.Map("/notlogin", signoutApp => signoutApp.Run(context => context.Authentication.SignInAsync("Cookies", app.Map("/notlogin", signoutApp => signoutApp.Run(context => context.Authentication.SignInAsync("Cookies",
new ClaimsPrincipal()))); new ClaimsPrincipal())));
}) })
@ -932,7 +943,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => options.LoginPath = new PathString("/login")); app.UseCookieAuthentication(new CookieAuthenticationOptions
{
LoginPath = new PathString("/login")
});
app.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.SignInAsync("Cookies", app.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.SignInAsync("Cookies",
new ClaimsPrincipal()))); new ClaimsPrincipal())));
}) })
@ -954,7 +968,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => options.LogoutPath = new PathString("/logout")); app.UseCookieAuthentication(new CookieAuthenticationOptions
{
LogoutPath = new PathString("/logout")
});
app.Map("/notlogout", signoutApp => signoutApp.Run(context => context.Authentication.SignOutAsync("Cookies"))); app.Map("/notlogout", signoutApp => signoutApp.Run(context => context.Authentication.SignOutAsync("Cookies")));
}) })
.ConfigureServices(services => services.AddAuthentication()); .ConfigureServices(services => services.AddAuthentication());
@ -971,7 +988,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => options.LogoutPath = new PathString("/logout")); app.UseCookieAuthentication(new CookieAuthenticationOptions
{
LogoutPath = new PathString("/logout")
});
app.Map("/logout", signoutApp => signoutApp.Run(context => context.Authentication.SignOutAsync("Cookies"))); app.Map("/logout", signoutApp => signoutApp.Run(context => context.Authentication.SignOutAsync("Cookies")));
}) })
.ConfigureServices(services => services.AddAuthentication()); .ConfigureServices(services => services.AddAuthentication());
@ -992,7 +1012,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => options.AccessDeniedPath = new PathString("/denied")); app.UseCookieAuthentication(new CookieAuthenticationOptions
{
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")));
}) })
.ConfigureServices(services => services.AddAuthentication()); .ConfigureServices(services => services.AddAuthentication());
@ -1012,7 +1035,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
.Configure(app => .Configure(app =>
app.Map("/base", map => app.Map("/base", map =>
{ {
map.UseCookieAuthentication(options => options.LoginPath = new PathString("/page")); map.UseCookieAuthentication(new CookieAuthenticationOptions
{
LoginPath = new PathString("/page")
});
map.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.ChallengeAsync("Cookies", new AuthenticationProperties() { RedirectUri = "/" }))); map.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.ChallengeAsync("Cookies", new AuthenticationProperties() { RedirectUri = "/" })));
})) }))
.ConfigureServices(services => services.AddAuthentication()); .ConfigureServices(services => services.AddAuthentication());
@ -1033,7 +1059,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
.Configure(app => .Configure(app =>
app.Map("/base", map => app.Map("/base", map =>
{ {
map.UseCookieAuthentication(options => options.AccessDeniedPath = new PathString("/denied")); map.UseCookieAuthentication(new CookieAuthenticationOptions
{
AccessDeniedPath = new PathString("/denied")
});
map.Map("/forbid", signoutApp => signoutApp.Run(context => context.Authentication.ForbidAsync("Cookies"))); map.Map("/forbid", signoutApp => signoutApp.Run(context => context.Authentication.ForbidAsync("Cookies")));
})) }))
.ConfigureServices(services => services.AddAuthentication()); .ConfigureServices(services => services.AddAuthentication());
@ -1054,10 +1083,10 @@ namespace Microsoft.AspNet.Authentication.Cookies
var builder1 = new WebApplicationBuilder() var builder1 = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => app.UseCookieAuthentication(new CookieAuthenticationOptions
{ {
options.TicketDataFormat = new TicketDataFormat(dp); TicketDataFormat = new TicketDataFormat(dp),
options.CookieName = "Cookie"; CookieName = "Cookie"
}); });
app.Use((context, next) => app.Use((context, next) =>
context.Authentication.SignInAsync("Cookies", context.Authentication.SignInAsync("Cookies",
@ -1073,11 +1102,11 @@ namespace Microsoft.AspNet.Authentication.Cookies
var builder2 = new WebApplicationBuilder() var builder2 = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => app.UseCookieAuthentication(new CookieAuthenticationOptions
{ {
options.AuthenticationScheme = "Cookies"; AuthenticationScheme = "Cookies",
options.CookieName = "Cookie"; CookieName = "Cookie",
options.TicketDataFormat = new TicketDataFormat(dp); TicketDataFormat = new TicketDataFormat(dp)
}); });
app.Use(async (context, next) => app.Use(async (context, next) =>
{ {
@ -1131,12 +1160,12 @@ namespace Microsoft.AspNet.Authentication.Cookies
return me; return me;
} }
private static TestServer CreateServer(Action<CookieAuthenticationOptions> configureOptions, Func<HttpContext, Task> testpath = null, Uri baseAddress = null, Action<ClaimsTransformationOptions> claimsTransform = null) private static TestServer CreateServer(CookieAuthenticationOptions options, Func<HttpContext, Task> testpath = null, Uri baseAddress = null, ClaimsTransformationOptions claimsTransform = null)
{ {
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(configureOptions); app.UseCookieAuthentication(options);
// app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie2" }); // app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie2" });
if (claimsTransform != null) if (claimsTransform != null)

View File

@ -30,23 +30,23 @@ namespace Microsoft.AspNet.Authentication.Facebook
var server = CreateServer( var server = CreateServer(
app => app =>
{ {
app.UseFacebookAuthentication(options => app.UseFacebookAuthentication(new FacebookOptions
{ {
options.AppId = "Test App Id"; AppId = "Test App Id",
options.AppSecret = "Test App Secret"; AppSecret = "Test App Secret",
options.Events = new OAuthEvents Events = new OAuthEvents
{ {
OnRedirectToAuthorizationEndpoint = context => OnRedirectToAuthorizationEndpoint = context =>
{ {
context.Response.Redirect(context.RedirectUri + "&custom=test"); context.Response.Redirect(context.RedirectUri + "&custom=test");
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}); });
app.UseCookieAuthentication(options => app.UseCookieAuthentication(new CookieAuthenticationOptions
{ {
options.AuthenticationScheme = "External"; AuthenticationScheme = "External",
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true
}); });
}, },
services => services =>
@ -73,11 +73,11 @@ namespace Microsoft.AspNet.Authentication.Facebook
{ {
var server = CreateServer(app => var server = CreateServer(app =>
app.Map("/base", map => { app.Map("/base", map => {
map.UseFacebookAuthentication(options => map.UseFacebookAuthentication(new FacebookOptions
{ {
options.AppId = "Test App Id"; AppId = "Test App Id",
options.AppSecret = "Test App Secret"; AppSecret = "Test App Secret",
options.SignInScheme = "External"; SignInScheme = "External"
}); });
map.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.ChallengeAsync("Facebook", new AuthenticationProperties() { RedirectUri = "/" }))); map.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.ChallengeAsync("Facebook", new AuthenticationProperties() { RedirectUri = "/" })));
}), }),
@ -100,11 +100,11 @@ namespace Microsoft.AspNet.Authentication.Facebook
var server = CreateServer( var server = CreateServer(
app => app =>
{ {
app.UseFacebookAuthentication(options => app.UseFacebookAuthentication(new FacebookOptions
{ {
options.AppId = "Test App Id"; AppId = "Test App Id",
options.AppSecret = "Test App Secret"; AppSecret = "Test App Secret",
options.SignInScheme = "External"; SignInScheme = "External"
}); });
app.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.ChallengeAsync("Facebook", new AuthenticationProperties() { RedirectUri = "/" }))); app.Map("/login", signoutApp => signoutApp.Run(context => context.Authentication.ChallengeAsync("Facebook", new AuthenticationProperties() { RedirectUri = "/" })));
}, },
@ -127,12 +127,15 @@ namespace Microsoft.AspNet.Authentication.Facebook
var server = CreateServer( var server = CreateServer(
app => app =>
{ {
app.UseFacebookAuthentication(options => app.UseFacebookAuthentication(new FacebookOptions
{ {
options.AppId = "Test App Id"; AppId = "Test App Id",
options.AppSecret = "Test App Secret"; AppSecret = "Test App Secret"
});
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "External"
}); });
app.UseCookieAuthentication(options => options.AuthenticationScheme = "External");
}, },
services => services =>
{ {
@ -165,13 +168,13 @@ namespace Microsoft.AspNet.Authentication.Facebook
app => app =>
{ {
app.UseCookieAuthentication(); app.UseCookieAuthentication();
app.UseFacebookAuthentication(options => app.UseFacebookAuthentication(new FacebookOptions
{ {
options.AppId = "Test App Id"; AppId = "Test App Id",
options.AppSecret = "Test App Secret"; AppSecret = "Test App Secret",
options.StateDataFormat = stateFormat; StateDataFormat = stateFormat,
options.UserInformationEndpoint = customUserInfoEndpoint; UserInformationEndpoint = customUserInfoEndpoint,
options.BackchannelHttpHandler = new TestHttpMessageHandler BackchannelHttpHandler = new TestHttpMessageHandler
{ {
Sender = req => Sender = req =>
{ {
@ -200,7 +203,7 @@ namespace Microsoft.AspNet.Authentication.Facebook
} }
return null; return null;
} }
}; }
}); });
}, },
services => services =>

View File

@ -28,10 +28,10 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task ChallengeWillTriggerRedirection() public async Task ChallengeWillTriggerRedirection()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret"
}); });
var transaction = await server.SendAsync("https://example.com/challenge"); var transaction = await server.SendAsync("https://example.com/challenge");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
@ -50,10 +50,10 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task SignInThrows() public async Task SignInThrows()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret"
}); });
var transaction = await server.SendAsync("https://example.com/signIn"); var transaction = await server.SendAsync("https://example.com/signIn");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -62,10 +62,10 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task SignOutThrows() public async Task SignOutThrows()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret"
}); });
var transaction = await server.SendAsync("https://example.com/signOut"); var transaction = await server.SendAsync("https://example.com/signOut");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -74,10 +74,10 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task ForbidThrows() public async Task ForbidThrows()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret"
}); });
var transaction = await server.SendAsync("https://example.com/signOut"); var transaction = await server.SendAsync("https://example.com/signOut");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -86,11 +86,11 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task Challenge401WillTriggerRedirection() public async Task Challenge401WillTriggerRedirection()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret",
options.AutomaticChallenge = true; AutomaticChallenge = true
}); });
var transaction = await server.SendAsync("https://example.com/401"); var transaction = await server.SendAsync("https://example.com/401");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
@ -105,10 +105,10 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task ChallengeWillSetCorrelationCookie() public async Task ChallengeWillSetCorrelationCookie()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret"
}); });
var transaction = await server.SendAsync("https://example.com/challenge"); var transaction = await server.SendAsync("https://example.com/challenge");
Assert.Contains(".AspNet.Correlation.Google=", transaction.SetCookie.Single()); Assert.Contains(".AspNet.Correlation.Google=", transaction.SetCookie.Single());
@ -117,11 +117,11 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task Challenge401WillSetCorrelationCookie() public async Task Challenge401WillSetCorrelationCookie()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret",
options.AutomaticChallenge = true; AutomaticChallenge = true
}); });
var transaction = await server.SendAsync("https://example.com/401"); var transaction = await server.SendAsync("https://example.com/401");
Assert.Contains(".AspNet.Correlation.Google=", transaction.SetCookie.Single()); Assert.Contains(".AspNet.Correlation.Google=", transaction.SetCookie.Single());
@ -130,10 +130,10 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task ChallengeWillSetDefaultScope() public async Task ChallengeWillSetDefaultScope()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret"
}); });
var transaction = await server.SendAsync("https://example.com/challenge"); var transaction = await server.SendAsync("https://example.com/challenge");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
@ -144,11 +144,11 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task Challenge401WillSetDefaultScope() public async Task Challenge401WillSetDefaultScope()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret",
options.AutomaticChallenge = true; AutomaticChallenge = true
}); });
var transaction = await server.SendAsync("https://example.com/401"); var transaction = await server.SendAsync("https://example.com/401");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
@ -159,11 +159,11 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task ChallengeWillUseAuthenticationPropertiesAsParameters() public async Task ChallengeWillUseAuthenticationPropertiesAsParameters()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret",
options.AutomaticChallenge = true; AutomaticChallenge = true
}, },
context => context =>
{ {
@ -195,18 +195,18 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task ChallengeWillTriggerApplyRedirectEvent() public async Task ChallengeWillTriggerApplyRedirectEvent()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret",
options.Events = new OAuthEvents Events = new OAuthEvents
{ {
OnRedirectToAuthorizationEndpoint = context => OnRedirectToAuthorizationEndpoint = context =>
{ {
context.Response.Redirect(context.RedirectUri + "&custom=test"); context.Response.Redirect(context.RedirectUri + "&custom=test");
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}); });
var transaction = await server.SendAsync("https://example.com/challenge"); var transaction = await server.SendAsync("https://example.com/challenge");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
@ -217,10 +217,10 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task AuthenticateWillFail() public async Task AuthenticateWillFail()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret"
}, },
async context => async context =>
{ {
@ -240,10 +240,10 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task ReplyPathWithoutStateQueryStringWillBeRejected() public async Task ReplyPathWithoutStateQueryStringWillBeRejected()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret"
}); });
var error = await Assert.ThrowsAnyAsync<Exception>(() => server.SendAsync("https://example.com/signin-google?code=TestCode")); var error = await Assert.ThrowsAnyAsync<Exception>(() => server.SendAsync("https://example.com/signin-google?code=TestCode"));
Assert.Equal("The oauth state was missing or invalid.", error.GetBaseException().Message); Assert.Equal("The oauth state was missing or invalid.", error.GetBaseException().Message);
@ -254,22 +254,19 @@ namespace Microsoft.AspNet.Authentication.Google
[InlineData(false)] [InlineData(false)]
public async Task ReplyPathWithErrorFails(bool redirect) public async Task ReplyPathWithErrorFails(bool redirect)
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret",
if (redirect) Events = redirect ? new OAuthEvents()
{ {
options.Events = new OAuthEvents() OnRemoteFailure = ctx =>
{ {
OnRemoteFailure = ctx => ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message));
{ ctx.HandleResponse();
ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message)); return Task.FromResult(0);
ctx.HandleResponse(); }
return Task.FromResult(0); } : new OAuthEvents()
}
};
}
}); });
var sendTask = server.SendAsync("https://example.com/signin-google?error=OMG&error_description=SoBad&error_uri=foobar"); var sendTask = server.SendAsync("https://example.com/signin-google?error=OMG&error_description=SoBad&error_uri=foobar");
if (redirect) if (redirect)
@ -291,13 +288,13 @@ namespace Microsoft.AspNet.Authentication.Google
public async Task ReplyPathWillAuthenticateValidAuthorizeCodeAndState(string claimsIssuer) public async Task ReplyPathWillAuthenticateValidAuthorizeCodeAndState(string claimsIssuer)
{ {
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest"));
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret",
options.StateDataFormat = stateFormat; StateDataFormat = stateFormat,
options.ClaimsIssuer = claimsIssuer; ClaimsIssuer = claimsIssuer,
options.BackchannelHttpHandler = new TestHttpMessageHandler BackchannelHttpHandler = new TestHttpMessageHandler
{ {
Sender = req => Sender = req =>
{ {
@ -335,7 +332,7 @@ namespace Microsoft.AspNet.Authentication.Google
throw new NotImplementedException(req.RequestUri.AbsoluteUri); throw new NotImplementedException(req.RequestUri.AbsoluteUri);
} }
}; }
}); });
var properties = new AuthenticationProperties(); var properties = new AuthenticationProperties();
var correlationKey = ".AspNet.Correlation.Google"; var correlationKey = ".AspNet.Correlation.Google";
@ -373,31 +370,28 @@ namespace Microsoft.AspNet.Authentication.Google
public async Task ReplyPathWillThrowIfCodeIsInvalid(bool redirect) public async Task ReplyPathWillThrowIfCodeIsInvalid(bool redirect)
{ {
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest"));
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret",
options.StateDataFormat = stateFormat; StateDataFormat = stateFormat,
options.BackchannelHttpHandler = new TestHttpMessageHandler BackchannelHttpHandler = new TestHttpMessageHandler
{ {
Sender = req => Sender = req =>
{ {
return ReturnJsonResponse(new { Error = "Error" }, return ReturnJsonResponse(new { Error = "Error" },
HttpStatusCode.BadRequest); HttpStatusCode.BadRequest);
} }
}; },
if (redirect) Events = redirect ? new OAuthEvents()
{ {
options.Events = new OAuthEvents() OnRemoteFailure = ctx =>
{ {
OnRemoteFailure = ctx => ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message));
{ ctx.HandleResponse();
ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message)); return Task.FromResult(0);
ctx.HandleResponse(); }
return Task.FromResult(0); } : new OAuthEvents()
}
};
}
}); });
var properties = new AuthenticationProperties(); var properties = new AuthenticationProperties();
var correlationKey = ".AspNet.Correlation.Google"; var correlationKey = ".AspNet.Correlation.Google";
@ -429,30 +423,27 @@ namespace Microsoft.AspNet.Authentication.Google
public async Task ReplyPathWillRejectIfAccessTokenIsMissing(bool redirect) public async Task ReplyPathWillRejectIfAccessTokenIsMissing(bool redirect)
{ {
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest"));
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret",
options.StateDataFormat = stateFormat; StateDataFormat = stateFormat,
options.BackchannelHttpHandler = new TestHttpMessageHandler BackchannelHttpHandler = new TestHttpMessageHandler
{ {
Sender = req => Sender = req =>
{ {
return ReturnJsonResponse(new object()); return ReturnJsonResponse(new object());
} }
}; },
if (redirect) Events = redirect ? new OAuthEvents()
{ {
options.Events = new OAuthEvents() OnRemoteFailure = ctx =>
{ {
OnRemoteFailure = ctx => ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message));
{ ctx.HandleResponse();
ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message)); return Task.FromResult(0);
ctx.HandleResponse(); }
return Task.FromResult(0); } : new OAuthEvents()
}
};
}
}); });
var properties = new AuthenticationProperties(); var properties = new AuthenticationProperties();
var correlationKey = ".AspNet.Correlation.Google"; var correlationKey = ".AspNet.Correlation.Google";
@ -481,12 +472,12 @@ namespace Microsoft.AspNet.Authentication.Google
public async Task AuthenticatedEventCanGetRefreshToken() public async Task AuthenticatedEventCanGetRefreshToken()
{ {
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest"));
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret",
options.StateDataFormat = stateFormat; StateDataFormat = stateFormat,
options.BackchannelHttpHandler = new TestHttpMessageHandler BackchannelHttpHandler = new TestHttpMessageHandler
{ {
Sender = req => Sender = req =>
{ {
@ -525,8 +516,8 @@ namespace Microsoft.AspNet.Authentication.Google
throw new NotImplementedException(req.RequestUri.AbsoluteUri); throw new NotImplementedException(req.RequestUri.AbsoluteUri);
} }
}; },
options.Events = new OAuthEvents Events = new OAuthEvents
{ {
OnCreatingTicket = context => OnCreatingTicket = context =>
{ {
@ -534,7 +525,7 @@ namespace Microsoft.AspNet.Authentication.Google
context.Ticket.Principal.AddIdentity(new ClaimsIdentity(new Claim[] { new Claim("RefreshToken", refreshToken, ClaimValueTypes.String, "Google") }, "Google")); context.Ticket.Principal.AddIdentity(new ClaimsIdentity(new Claim[] { new Claim("RefreshToken", refreshToken, ClaimValueTypes.String, "Google") }, "Google"));
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}); });
var properties = new AuthenticationProperties(); var properties = new AuthenticationProperties();
var correlationKey = ".AspNet.Correlation.Google"; var correlationKey = ".AspNet.Correlation.Google";
@ -561,12 +552,12 @@ namespace Microsoft.AspNet.Authentication.Google
public async Task NullRedirectUriWillRedirectToSlash() public async Task NullRedirectUriWillRedirectToSlash()
{ {
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest"));
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret",
options.StateDataFormat = stateFormat; StateDataFormat = stateFormat,
options.BackchannelHttpHandler = new TestHttpMessageHandler BackchannelHttpHandler = new TestHttpMessageHandler
{ {
Sender = req => Sender = req =>
{ {
@ -605,15 +596,15 @@ namespace Microsoft.AspNet.Authentication.Google
throw new NotImplementedException(req.RequestUri.AbsoluteUri); throw new NotImplementedException(req.RequestUri.AbsoluteUri);
} }
}; },
options.Events = new OAuthEvents Events = new OAuthEvents
{ {
OnTicketReceived = context => OnTicketReceived = context =>
{ {
context.Ticket.Properties.RedirectUri = null; context.Ticket.Properties.RedirectUri = null;
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}); });
var properties = new AuthenticationProperties(); var properties = new AuthenticationProperties();
var correlationKey = ".AspNet.Correlation.Google"; var correlationKey = ".AspNet.Correlation.Google";
@ -634,13 +625,13 @@ namespace Microsoft.AspNet.Authentication.Google
public async Task ValidateAuthenticatedContext() public async Task ValidateAuthenticatedContext()
{ {
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest"));
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret",
options.StateDataFormat = stateFormat; StateDataFormat = stateFormat,
options.AccessType = "offline"; AccessType = "offline",
options.Events = new OAuthEvents() Events = new OAuthEvents()
{ {
OnCreatingTicket = context => OnCreatingTicket = context =>
{ {
@ -655,8 +646,8 @@ namespace Microsoft.AspNet.Authentication.Google
Assert.Equal(GoogleHelper.GetGivenName(context.User), "Test Given Name"); Assert.Equal(GoogleHelper.GetGivenName(context.User), "Test Given Name");
return Task.FromResult(0); return Task.FromResult(0);
} }
}; },
options.BackchannelHttpHandler = new TestHttpMessageHandler BackchannelHttpHandler = new TestHttpMessageHandler
{ {
Sender = req => Sender = req =>
{ {
@ -695,7 +686,7 @@ namespace Microsoft.AspNet.Authentication.Google
throw new NotImplementedException(req.RequestUri.AbsoluteUri); throw new NotImplementedException(req.RequestUri.AbsoluteUri);
} }
}; }
}); });
var properties = new AuthenticationProperties(); var properties = new AuthenticationProperties();
@ -717,10 +708,10 @@ namespace Microsoft.AspNet.Authentication.Google
[Fact] [Fact]
public async Task NoStateCausesException() public async Task NoStateCausesException()
{ {
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret"
}); });
//Post a message to the Google middleware //Post a message to the Google middleware
@ -732,11 +723,11 @@ namespace Microsoft.AspNet.Authentication.Google
public async Task CanRedirectOnError() public async Task CanRedirectOnError()
{ {
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest"));
var server = CreateServer(options => var server = CreateServer(new GoogleOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret",
options.Events = new OAuthEvents() Events = new OAuthEvents()
{ {
OnRemoteFailure = ctx => OnRemoteFailure = ctx =>
{ {
@ -744,7 +735,7 @@ namespace Microsoft.AspNet.Authentication.Google
ctx.HandleResponse(); ctx.HandleResponse();
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}); });
//Post a message to the Google middleware //Post a message to the Google middleware
@ -764,17 +755,17 @@ namespace Microsoft.AspNet.Authentication.Google
return res; return res;
} }
private static TestServer CreateServer(Action<GoogleOptions> configureOptions, Func<HttpContext, Task> testpath = null) private static TestServer CreateServer(GoogleOptions options, Func<HttpContext, Task> testpath = null)
{ {
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => app.UseCookieAuthentication(new CookieAuthenticationOptions
{ {
options.AuthenticationScheme = TestExtensions.CookieAuthenticationScheme; AuthenticationScheme = TestExtensions.CookieAuthenticationScheme,
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true
}); });
app.UseGoogleAuthentication(configureOptions); app.UseGoogleAuthentication(options);
app.UseClaimsTransformation(p => app.UseClaimsTransformation(p =>
{ {
var id = new ClaimsIdentity("xform"); var id = new ClaimsIdentity("xform");
@ -833,7 +824,7 @@ namespace Microsoft.AspNet.Authentication.Google
}) })
.ConfigureServices(services => .ConfigureServices(services =>
{ {
services.AddAuthentication(options => options.SignInScheme = TestExtensions.CookieAuthenticationScheme); services.AddAuthentication(authOptions => authOptions.SignInScheme = TestExtensions.CookieAuthenticationScheme);
}); });
return new TestServer(builder); return new TestServer(builder);
} }

View File

@ -2,6 +2,7 @@
// 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.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Security.Claims; using System.Security.Claims;
@ -27,14 +28,14 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
// https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/179 // https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/179
public async Task BearerTokenValidation() public async Task BearerTokenValidation()
{ {
var server = CreateServer(options => var options = new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
Authority = "https://login.windows.net/tushartest.onmicrosoft.com",
options.Authority = "https://login.windows.net/tushartest.onmicrosoft.com"; Audience = "https://TusharTest.onmicrosoft.com/TodoListService-ManualJwt"
options.Audience = "https://TusharTest.onmicrosoft.com/TodoListService-ManualJwt"; };
options.TokenValidationParameters.ValidateLifetime = false; options.TokenValidationParameters.ValidateLifetime = false;
}); var server = CreateServer(options);
var newBearerToken = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImtyaU1QZG1Cdng2OHNrVDgtbVBBQjNCc2VlQSJ9.eyJhdWQiOiJodHRwczovL1R1c2hhclRlc3Qub25taWNyb3NvZnQuY29tL1RvZG9MaXN0U2VydmljZS1NYW51YWxKd3QiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9hZmJlY2UwMy1hZWFhLTRmM2YtODVlNy1jZTA4ZGQyMGNlNTAvIiwiaWF0IjoxNDE4MzMwNjE0LCJuYmYiOjE0MTgzMzA2MTQsImV4cCI6MTQxODMzNDUxNCwidmVyIjoiMS4wIiwidGlkIjoiYWZiZWNlMDMtYWVhYS00ZjNmLTg1ZTctY2UwOGRkMjBjZTUwIiwiYW1yIjpbInB3ZCJdLCJvaWQiOiI1Mzk3OTdjMi00MDE5LTQ2NTktOWRiNS03MmM0Yzc3NzhhMzMiLCJ1cG4iOiJWaWN0b3JAVHVzaGFyVGVzdC5vbm1pY3Jvc29mdC5jb20iLCJ1bmlxdWVfbmFtZSI6IlZpY3RvckBUdXNoYXJUZXN0Lm9ubWljcm9zb2Z0LmNvbSIsInN1YiI6IkQyMm9aMW9VTzEzTUFiQXZrdnFyd2REVE80WXZJdjlzMV9GNWlVOVUwYnciLCJmYW1pbHlfbmFtZSI6Ikd1cHRhIiwiZ2l2ZW5fbmFtZSI6IlZpY3RvciIsImFwcGlkIjoiNjEzYjVhZjgtZjJjMy00MWI2LWExZGMtNDE2Yzk3ODAzMGI3IiwiYXBwaWRhY3IiOiIwIiwic2NwIjoidXNlcl9pbXBlcnNvbmF0aW9uIiwiYWNyIjoiMSJ9.N_Kw1EhoVGrHbE6hOcm7ERdZ7paBQiNdObvp2c6T6n5CE8p0fZqmUd-ya_EqwElcD6SiKSiP7gj0gpNUnOJcBl_H2X8GseaeeMxBrZdsnDL8qecc6_ygHruwlPltnLTdka67s1Ow4fDSHaqhVTEk6lzGmNEcbNAyb0CxQxU6o7Fh0yHRiWoLsT8yqYk8nKzsHXfZBNby4aRo3_hXaa4i0SZLYfDGGYPdttG4vT_u54QGGd4Wzbonv2gjDlllOVGOwoJS6kfl1h8mk0qxdiIaT_ChbDWgkWvTB7bTvBE-EgHgV0XmAo0WtJeSxgjsG3KhhEPsONmqrSjhIUV4IVnF2w"; var newBearerToken = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImtyaU1QZG1Cdng2OHNrVDgtbVBBQjNCc2VlQSJ9.eyJhdWQiOiJodHRwczovL1R1c2hhclRlc3Qub25taWNyb3NvZnQuY29tL1RvZG9MaXN0U2VydmljZS1NYW51YWxKd3QiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9hZmJlY2UwMy1hZWFhLTRmM2YtODVlNy1jZTA4ZGQyMGNlNTAvIiwiaWF0IjoxNDE4MzMwNjE0LCJuYmYiOjE0MTgzMzA2MTQsImV4cCI6MTQxODMzNDUxNCwidmVyIjoiMS4wIiwidGlkIjoiYWZiZWNlMDMtYWVhYS00ZjNmLTg1ZTctY2UwOGRkMjBjZTUwIiwiYW1yIjpbInB3ZCJdLCJvaWQiOiI1Mzk3OTdjMi00MDE5LTQ2NTktOWRiNS03MmM0Yzc3NzhhMzMiLCJ1cG4iOiJWaWN0b3JAVHVzaGFyVGVzdC5vbm1pY3Jvc29mdC5jb20iLCJ1bmlxdWVfbmFtZSI6IlZpY3RvckBUdXNoYXJUZXN0Lm9ubWljcm9zb2Z0LmNvbSIsInN1YiI6IkQyMm9aMW9VTzEzTUFiQXZrdnFyd2REVE80WXZJdjlzMV9GNWlVOVUwYnciLCJmYW1pbHlfbmFtZSI6Ikd1cHRhIiwiZ2l2ZW5fbmFtZSI6IlZpY3RvciIsImFwcGlkIjoiNjEzYjVhZjgtZjJjMy00MWI2LWExZGMtNDE2Yzk3ODAzMGI3IiwiYXBwaWRhY3IiOiIwIiwic2NwIjoidXNlcl9pbXBlcnNvbmF0aW9uIiwiYWNyIjoiMSJ9.N_Kw1EhoVGrHbE6hOcm7ERdZ7paBQiNdObvp2c6T6n5CE8p0fZqmUd-ya_EqwElcD6SiKSiP7gj0gpNUnOJcBl_H2X8GseaeeMxBrZdsnDL8qecc6_ygHruwlPltnLTdka67s1Ow4fDSHaqhVTEk6lzGmNEcbNAyb0CxQxU6o7Fh0yHRiWoLsT8yqYk8nKzsHXfZBNby4aRo3_hXaa4i0SZLYfDGGYPdttG4vT_u54QGGd4Wzbonv2gjDlllOVGOwoJS6kfl1h8mk0qxdiIaT_ChbDWgkWvTB7bTvBE-EgHgV0XmAo0WtJeSxgjsG3KhhEPsONmqrSjhIUV4IVnF2w";
var response = await SendAsync(server, "http://example.com/oauth", newBearerToken); var response = await SendAsync(server, "http://example.com/oauth", newBearerToken);
@ -44,9 +45,9 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task SignInThrows() public async Task SignInThrows()
{ {
var server = CreateServer(options => var server = CreateServer(new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true
}); });
var transaction = await server.SendAsync("https://example.com/signIn"); var transaction = await server.SendAsync("https://example.com/signIn");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -55,9 +56,9 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task SignOutThrows() public async Task SignOutThrows()
{ {
var server = CreateServer(options => var server = CreateServer(new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true
}); });
var transaction = await server.SendAsync("https://example.com/signOut"); var transaction = await server.SendAsync("https://example.com/signOut");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -67,11 +68,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task CustomHeaderReceived() public async Task CustomHeaderReceived()
{ {
var server = CreateServer(options => var server = CreateServer(new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
Events = new JwtBearerEvents()
options.Events = new JwtBearerEvents()
{ {
OnReceivingToken = context => OnReceivingToken = context =>
{ {
@ -90,7 +90,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
return Task.FromResult<object>(null); return Task.FromResult<object>(null);
} }
}; }
}); });
var response = await SendAsync(server, "http://example.com/oauth", "someHeader someblob"); var response = await SendAsync(server, "http://example.com/oauth", "someHeader someblob");
@ -101,7 +101,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task NoHeaderReceived() public async Task NoHeaderReceived()
{ {
var server = CreateServer(options => { }); var server = CreateServer(new JwtBearerOptions());
var response = await SendAsync(server, "http://example.com/oauth"); var response = await SendAsync(server, "http://example.com/oauth");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
} }
@ -109,7 +109,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task HeaderWithoutBearerReceived() public async Task HeaderWithoutBearerReceived()
{ {
var server = CreateServer(options => { }); var server = CreateServer(new JwtBearerOptions());
var response = await SendAsync(server, "http://example.com/oauth","Token"); var response = await SendAsync(server, "http://example.com/oauth","Token");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
} }
@ -117,9 +117,9 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task UnrecognizedTokenReceived() public async Task UnrecognizedTokenReceived()
{ {
var server = CreateServer(options => var server = CreateServer(new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true
}); });
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
@ -130,12 +130,13 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task InvalidTokenReceived() public async Task InvalidTokenReceived()
{ {
var server = CreateServer(options => var options = new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true
options.SecurityTokenValidators.Clear(); };
options.SecurityTokenValidators.Add(new InvalidTokenValidator()); options.SecurityTokenValidators.Clear();
}); options.SecurityTokenValidators.Add(new InvalidTokenValidator());
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
@ -145,11 +146,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task CustomTokenReceived() public async Task CustomTokenReceived()
{ {
var server = CreateServer(options => var server = CreateServer(new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
Events = new JwtBearerEvents()
options.Events = new JwtBearerEvents()
{ {
OnReceivedToken = context => OnReceivedToken = context =>
{ {
@ -168,7 +168,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
return Task.FromResult<object>(null); return Task.FromResult<object>(null);
} }
}; }
}); });
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
@ -179,11 +179,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task CustomTokenValidated() public async Task CustomTokenValidated()
{ {
var server = CreateServer(options => var options = new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
Events = new JwtBearerEvents()
options.Events = new JwtBearerEvents()
{ {
OnValidatedToken = context => OnValidatedToken = context =>
{ {
@ -203,10 +202,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
return Task.FromResult<object>(null); return Task.FromResult<object>(null);
} }
}; }
};
options.SecurityTokenValidators.Add(new BlobTokenValidator(options.AuthenticationScheme)); options.SecurityTokenValidators.Add(new BlobTokenValidator(options.AuthenticationScheme));
}); var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
@ -216,11 +215,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task RetrievingTokenFromAlternateLocation() public async Task RetrievingTokenFromAlternateLocation()
{ {
var server = CreateServer(options => var server = CreateServer(new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
Events = new JwtBearerEvents()
options.Events = new JwtBearerEvents()
{ {
OnReceivingToken = context => OnReceivingToken = context =>
{ {
@ -244,7 +242,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
return Task.FromResult<object>(null); return Task.FromResult<object>(null);
} }
}; }
}); });
var response = await SendAsync(server, "http://example.com/oauth", "Bearer Token"); var response = await SendAsync(server, "http://example.com/oauth", "Bearer Token");
@ -255,9 +253,9 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task BearerTurns401To403IfAuthenticated() public async Task BearerTurns401To403IfAuthenticated()
{ {
var server = CreateServer(options => var server = CreateServer(new JwtBearerOptions
{ {
options.Events = new JwtBearerEvents() Events = new JwtBearerEvents()
{ {
OnReceivedToken = context => OnReceivedToken = context =>
{ {
@ -276,7 +274,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
return Task.FromResult<object>(null); return Task.FromResult<object>(null);
} }
}; }
}); });
var response = await SendAsync(server, "http://example.com/unauthorized", "Bearer Token"); var response = await SendAsync(server, "http://example.com/unauthorized", "Bearer Token");
@ -286,9 +284,9 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task BearerDoesNothingTo401IfNotAuthenticated() public async Task BearerDoesNothingTo401IfNotAuthenticated()
{ {
var server = CreateServer(options => var server = CreateServer(new JwtBearerOptions
{ {
options.Events = new JwtBearerEvents() Events = new JwtBearerEvents()
{ {
OnReceivedToken = context => OnReceivedToken = context =>
{ {
@ -307,7 +305,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
return Task.FromResult<object>(null); return Task.FromResult<object>(null);
} }
}; }
}); });
var response = await SendAsync(server, "http://example.com/unauthorized"); var response = await SendAsync(server, "http://example.com/unauthorized");
@ -317,11 +315,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task EventOnReceivingTokenSkipped_NoMoreEventsExecuted() public async Task EventOnReceivingTokenSkipped_NoMoreEventsExecuted()
{ {
var server = CreateServer(options => var server = CreateServer(new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
Events = new JwtBearerEvents()
options.Events = new JwtBearerEvents()
{ {
OnReceivingToken = context => OnReceivingToken = context =>
{ {
@ -344,7 +341,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{ {
throw new NotImplementedException(); throw new NotImplementedException();
}, },
}; }
}); });
var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token"); var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token");
@ -355,11 +352,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task EventOnReceivedTokenSkipped_NoMoreEventsExecuted() public async Task EventOnReceivedTokenSkipped_NoMoreEventsExecuted()
{ {
var server = CreateServer(options => var server = CreateServer(new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
Events = new JwtBearerEvents()
options.Events = new JwtBearerEvents()
{ {
OnReceivedToken = context => OnReceivedToken = context =>
{ {
@ -378,7 +374,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{ {
throw new NotImplementedException(); throw new NotImplementedException();
}, },
}; }
}); });
var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token"); var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token");
@ -389,12 +385,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task EventOnValidatedTokenSkipped_NoMoreEventsExecuted() public async Task EventOnValidatedTokenSkipped_NoMoreEventsExecuted()
{ {
var server = CreateServer(options => var options = new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
options.SecurityTokenValidators.Clear(); Events = new JwtBearerEvents()
options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT"));
options.Events = new JwtBearerEvents()
{ {
OnValidatedToken = context => OnValidatedToken = context =>
{ {
@ -409,8 +403,11 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{ {
throw new NotImplementedException(); throw new NotImplementedException();
}, },
}; }
}); };
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT"));
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token"); var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token");
Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
@ -420,12 +417,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task EventOnAuthenticationFailedSkipped_NoMoreEventsExecuted() public async Task EventOnAuthenticationFailedSkipped_NoMoreEventsExecuted()
{ {
var server = CreateServer(options => var options = new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
options.SecurityTokenValidators.Clear(); Events = new JwtBearerEvents()
options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT"));
options.Events = new JwtBearerEvents()
{ {
OnValidatedToken = context => OnValidatedToken = context =>
{ {
@ -440,8 +435,11 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{ {
throw new NotImplementedException(); throw new NotImplementedException();
}, },
}; }
}); };
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT"));
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token"); var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token");
Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
@ -451,18 +449,18 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
[Fact] [Fact]
public async Task EventOnChallengeSkipped_ResponseNotModified() public async Task EventOnChallengeSkipped_ResponseNotModified()
{ {
var server = CreateServer(options => var server = CreateServer(new JwtBearerOptions
{ {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
options.AutomaticChallenge = true; AutomaticChallenge = true,
options.Events = new JwtBearerEvents() Events = new JwtBearerEvents()
{ {
OnChallenge = context => OnChallenge = context =>
{ {
context.SkipToNextMiddleware(); context.SkipToNextMiddleware();
return Task.FromResult(0); return Task.FromResult(0);
}, },
}; }
}); });
var response = await SendAsync(server, "http://example.com/unauthorized", "Bearer Token"); var response = await SendAsync(server, "http://example.com/unauthorized", "Bearer Token");
@ -535,14 +533,14 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
} }
} }
private static TestServer CreateServer(Action<JwtBearerOptions> configureOptions, Func<HttpContext, bool> handler = null) private static TestServer CreateServer(JwtBearerOptions options, Func<HttpContext, bool> handler = null)
{ {
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
if (configureOptions != null) if (options != null)
{ {
app.UseJwtBearerAuthentication(configureOptions); app.UseJwtBearerAuthentication(options);
} }
app.Use(async (context, next) => app.Use(async (context, next) =>

View File

@ -8,7 +8,6 @@ using System.Security.Claims;
using System.Text; using System.Text;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Threading.Tasks; using System.Threading.Tasks;
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;
@ -27,19 +26,18 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount
[Fact] [Fact]
public async Task ChallengeWillTriggerApplyRedirectEvent() public async Task ChallengeWillTriggerApplyRedirectEvent()
{ {
var server = CreateServer( var server = CreateServer(new MicrosoftAccountOptions
options =>
{ {
options.ClientId = "Test Client Id"; ClientId = "Test Client Id",
options.ClientSecret = "Test Client Secret"; ClientSecret = "Test Client Secret",
options.Events = new OAuthEvents Events = new OAuthEvents
{ {
OnRedirectToAuthorizationEndpoint = context => OnRedirectToAuthorizationEndpoint = context =>
{ {
context.Response.Redirect(context.RedirectUri + "&custom=test"); context.Response.Redirect(context.RedirectUri + "&custom=test");
return Task.FromResult(0); return Task.FromResult(0);
} }
}; }
}); });
var transaction = await server.SendAsync("http://example.com/challenge"); var transaction = await server.SendAsync("http://example.com/challenge");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
@ -50,10 +48,10 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount
[Fact] [Fact]
public async Task SignInThrows() public async Task SignInThrows()
{ {
var server = CreateServer(options => var server = CreateServer(new MicrosoftAccountOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret"
}); });
var transaction = await server.SendAsync("https://example.com/signIn"); var transaction = await server.SendAsync("https://example.com/signIn");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -62,10 +60,10 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount
[Fact] [Fact]
public async Task SignOutThrows() public async Task SignOutThrows()
{ {
var server = CreateServer(options => var server = CreateServer(new MicrosoftAccountOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret"
}); });
var transaction = await server.SendAsync("https://example.com/signOut"); var transaction = await server.SendAsync("https://example.com/signOut");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -74,10 +72,10 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount
[Fact] [Fact]
public async Task ForbidThrows() public async Task ForbidThrows()
{ {
var server = CreateServer(options => var server = CreateServer(new MicrosoftAccountOptions
{ {
options.ClientId = "Test Id"; ClientId = "Test Id",
options.ClientSecret = "Test Secret"; ClientSecret = "Test Secret"
}); });
var transaction = await server.SendAsync("https://example.com/signOut"); var transaction = await server.SendAsync("https://example.com/signOut");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -86,11 +84,10 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount
[Fact] [Fact]
public async Task ChallengeWillTriggerRedirection() public async Task ChallengeWillTriggerRedirection()
{ {
var server = CreateServer( var server = CreateServer(new MicrosoftAccountOptions
options => {
{ ClientId = "Test Client Id",
options.ClientId = "Test Client Id"; ClientSecret = "Test Client Secret"
options.ClientSecret = "Test Client Secret";
}); });
var transaction = await server.SendAsync("http://example.com/challenge"); var transaction = await server.SendAsync("http://example.com/challenge");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
@ -107,13 +104,12 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount
public async Task AuthenticatedEventCanGetRefreshToken() public async Task AuthenticatedEventCanGetRefreshToken()
{ {
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("MsftTest")); var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("MsftTest"));
var server = CreateServer( var server = CreateServer(new MicrosoftAccountOptions
options => {
{ ClientId = "Test Client Id",
options.ClientId = "Test Client Id"; ClientSecret = "Test Client Secret",
options.ClientSecret = "Test Client Secret"; StateDataFormat = stateFormat,
options.StateDataFormat = stateFormat; BackchannelHttpHandler = new TestHttpMessageHandler
options.BackchannelHttpHandler = new TestHttpMessageHandler
{ {
Sender = req => Sender = req =>
{ {
@ -144,8 +140,8 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount
return null; return null;
} }
}; },
options.Events = new OAuthEvents Events = new OAuthEvents
{ {
OnCreatingTicket = context => OnCreatingTicket = context =>
{ {
@ -153,7 +149,7 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount
context.Ticket.Principal.AddIdentity(new ClaimsIdentity(new Claim[] { new Claim("RefreshToken", refreshToken, ClaimValueTypes.String, "Microsoft") }, "Microsoft")); context.Ticket.Principal.AddIdentity(new ClaimsIdentity(new Claim[] { new Claim("RefreshToken", refreshToken, ClaimValueTypes.String, "Microsoft") }, "Microsoft"));
return Task.FromResult<object>(null); return Task.FromResult<object>(null);
} }
}; }
}); });
var properties = new AuthenticationProperties(); var properties = new AuthenticationProperties();
var correlationKey = ".AspNet.Correlation.Microsoft"; var correlationKey = ".AspNet.Correlation.Microsoft";
@ -176,17 +172,17 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount
Assert.Equal("Test Refresh Token", transaction.FindClaimValue("RefreshToken")); Assert.Equal("Test Refresh Token", transaction.FindClaimValue("RefreshToken"));
} }
private static TestServer CreateServer(Action<MicrosoftAccountOptions> configureOptions) private static TestServer CreateServer(MicrosoftAccountOptions options)
{ {
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => app.UseCookieAuthentication(new CookieAuthenticationOptions
{ {
options.AuthenticationScheme = TestExtensions.CookieAuthenticationScheme; AuthenticationScheme = TestExtensions.CookieAuthenticationScheme,
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true
}); });
app.UseMicrosoftAccountAuthentication(configureOptions); app.UseMicrosoftAccountAuthentication(options);
app.Use(async (context, next) => app.Use(async (context, next) =>
{ {
@ -221,9 +217,9 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount
.ConfigureServices(services => .ConfigureServices(services =>
{ {
services.AddAuthentication(); services.AddAuthentication();
services.Configure<SharedAuthenticationOptions>(options => services.Configure<SharedAuthenticationOptions>(authOptions =>
{ {
options.SignInScheme = TestExtensions.CookieAuthenticationScheme; authOptions.SignInScheme = TestExtensions.CookieAuthenticationScheme;
}); });
}); });
return new TestServer(builder); return new TestServer(builder);

View File

@ -15,6 +15,7 @@ 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;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Xunit; using Xunit;
@ -31,20 +32,20 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
private const string ExpectedStateParameter = "expectedState"; private const string ExpectedStateParameter = "expectedState";
[Theory, MemberData(nameof(AuthenticateCoreStateDataSet))] [Theory, MemberData(nameof(AuthenticateCoreStateDataSet))]
public async Task AuthenticateCoreState(Action<OpenIdConnectOptions> action, OpenIdConnectMessage message) public async Task AuthenticateCoreState(OpenIdConnectOptions option, OpenIdConnectMessage message)
{ {
var handler = new OpenIdConnectHandlerForTestingAuthenticate(); var handler = new OpenIdConnectHandlerForTestingAuthenticate();
var server = CreateServer(action, UrlEncoder.Default, handler); var server = CreateServer(option, UrlEncoder.Default, handler);
await server.CreateClient().PostAsync("http://localhost", new FormUrlEncodedContent(message.Parameters.Where(pair => pair.Value != null))); await server.CreateClient().PostAsync("http://localhost", new FormUrlEncodedContent(message.Parameters.Where(pair => pair.Value != null)));
} }
public static TheoryData<Action<OpenIdConnectOptions>, OpenIdConnectMessage> AuthenticateCoreStateDataSet public static TheoryData<OpenIdConnectOptions, OpenIdConnectMessage> AuthenticateCoreStateDataSet
{ {
get get
{ {
var formater = new AuthenticationPropertiesFormaterKeyValue(); var formater = new AuthenticationPropertiesFormaterKeyValue();
var properties = new AuthenticationProperties(); var properties = new AuthenticationProperties();
var dataset = new TheoryData<Action<OpenIdConnectOptions>, OpenIdConnectMessage>(); var dataset = new TheoryData<OpenIdConnectOptions, OpenIdConnectMessage>();
// expected user state is added to the message.Parameters.Items[ExpectedStateParameter] // expected user state is added to the message.Parameters.Items[ExpectedStateParameter]
// Userstate == null // Userstate == null
@ -52,7 +53,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
message.State = UrlEncoder.Default.Encode(formater.Protect(properties)); message.State = UrlEncoder.Default.Encode(formater.Protect(properties));
message.Code = Guid.NewGuid().ToString(); message.Code = Guid.NewGuid().ToString();
message.Parameters.Add(ExpectedStateParameter, null); message.Parameters.Add(ExpectedStateParameter, null);
dataset.Add(SetStateOptions, message); dataset.Add(GetStateOptions(), message);
// Userstate != null // Userstate != null
message = new OpenIdConnectMessage(); message = new OpenIdConnectMessage();
@ -62,15 +63,16 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
properties.Items.Add(OpenIdConnectDefaults.UserstatePropertiesKey, userstate); properties.Items.Add(OpenIdConnectDefaults.UserstatePropertiesKey, userstate);
message.State = UrlEncoder.Default.Encode(formater.Protect(properties)); message.State = UrlEncoder.Default.Encode(formater.Protect(properties));
message.Parameters.Add(ExpectedStateParameter, userstate); message.Parameters.Add(ExpectedStateParameter, userstate);
dataset.Add(SetStateOptions, message); dataset.Add(GetStateOptions(), message);
return dataset; return dataset;
} }
} }
// Setup an event to check for expected state. // Setup an event to check for expected state.
// The state gets set by the runtime after the 'MessageReceivedContext' // The state gets set by the runtime after the 'MessageReceivedContext'
private static void SetStateOptions(OpenIdConnectOptions options) private static OpenIdConnectOptions GetStateOptions()
{ {
var options = new OpenIdConnectOptions();
options.AuthenticationScheme = "OpenIdConnectHandlerTest"; options.AuthenticationScheme = "OpenIdConnectHandlerTest";
options.ConfigurationManager = TestUtilities.DefaultOpenIdConnectConfigurationManager; options.ConfigurationManager = TestUtilities.DefaultOpenIdConnectConfigurationManager;
options.ClientId = Guid.NewGuid().ToString(); options.ClientId = Guid.NewGuid().ToString();
@ -91,16 +93,15 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
return Task.FromResult<object>(null); return Task.FromResult<object>(null);
} }
}; };
return options;
} }
private static TestServer CreateServer(Action<OpenIdConnectOptions> configureOptions, UrlEncoder encoder, OpenIdConnectHandler handler = null) private static TestServer CreateServer(OpenIdConnectOptions options, UrlEncoder encoder, OpenIdConnectHandler handler = null)
{ {
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
var options = new OpenIdConnectOptions(); app.UseMiddleware<OpenIdConnectMiddlewareForTestingAuthenticate>(Options.Create(options), encoder, handler);
configureOptions(options);
app.UseMiddleware<OpenIdConnectMiddlewareForTestingAuthenticate>(options, encoder, handler);
app.Use(async (context, next) => app.Use(async (context, next) =>
{ {
await next(); await next();

View File

@ -4,6 +4,7 @@
using System; using System;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using Microsoft.AspNet.Authentication.OpenIdConnect; using Microsoft.AspNet.Authentication.OpenIdConnect;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -27,7 +28,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
UrlEncoder encoder, UrlEncoder encoder,
IServiceProvider services, IServiceProvider services,
IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<SharedAuthenticationOptions> sharedOptions,
OpenIdConnectOptions options, IOptions<OpenIdConnectOptions> options,
HtmlEncoder htmlEncoder, HtmlEncoder htmlEncoder,
OpenIdConnectHandler handler = null OpenIdConnectHandler handler = null
) )

View File

@ -42,12 +42,12 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
[Fact] [Fact]
public async Task ChallengeWillIssueHtmlFormWhenEnabled() public async Task ChallengeWillIssueHtmlFormWhenEnabled()
{ {
var server = CreateServer(options => var server = CreateServer(new OpenIdConnectOptions
{ {
options.Authority = DefaultAuthority; Authority = DefaultAuthority,
options.ClientId = "Test Id"; ClientId = "Test Id",
options.Configuration = TestUtilities.DefaultOpenIdConnectConfiguration; Configuration = TestUtilities.DefaultOpenIdConnectConfiguration,
options.AuthenticationMethod = OpenIdConnectRedirectBehavior.FormPost; AuthenticationMethod = OpenIdConnectRedirectBehavior.FormPost
}); });
var transaction = await SendAsync(server, DefaultHost + Challenge); var transaction = await SendAsync(server, DefaultHost + Challenge);
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -61,10 +61,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
var stateDataFormat = new AuthenticationPropertiesFormaterKeyValue(); var stateDataFormat = new AuthenticationPropertiesFormaterKeyValue();
var queryValues = ExpectedQueryValues.Defaults(DefaultAuthority); var queryValues = ExpectedQueryValues.Defaults(DefaultAuthority);
queryValues.State = OpenIdConnectDefaults.AuthenticationPropertiesKey + "=" + stateDataFormat.Protect(new AuthenticationProperties()); queryValues.State = OpenIdConnectDefaults.AuthenticationPropertiesKey + "=" + stateDataFormat.Protect(new AuthenticationProperties());
var server = CreateServer(options => var server = CreateServer(GetOptions(DefaultParameters(), queryValues));
{
SetOptions(options, DefaultParameters(), queryValues);
});
var transaction = await SendAsync(server, DefaultHost + Challenge); var transaction = await SendAsync(server, DefaultHost + Challenge);
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
@ -74,11 +71,11 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
[Fact] [Fact]
public async Task ChallengeWillSetNonceAndStateCookies() public async Task ChallengeWillSetNonceAndStateCookies()
{ {
var server = CreateServer(options => var server = CreateServer(new OpenIdConnectOptions
{ {
options.Authority = DefaultAuthority; Authority = DefaultAuthority,
options.ClientId = "Test Id"; ClientId = "Test Id",
options.Configuration = TestUtilities.DefaultOpenIdConnectConfiguration; Configuration = TestUtilities.DefaultOpenIdConnectConfiguration
}); });
var transaction = await SendAsync(server, DefaultHost + Challenge); var transaction = await SendAsync(server, DefaultHost + Challenge);
@ -95,10 +92,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
public async Task ChallengeWillUseOptionsProperties() public async Task ChallengeWillUseOptionsProperties()
{ {
var queryValues = new ExpectedQueryValues(DefaultAuthority); var queryValues = new ExpectedQueryValues(DefaultAuthority);
var server = CreateServer(options => var server = CreateServer(GetOptions(DefaultParameters(), queryValues));
{
SetOptions(options, DefaultParameters(), queryValues);
});
var transaction = await SendAsync(server, DefaultHost + Challenge); var transaction = await SendAsync(server, DefaultHost + Challenge);
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
@ -121,7 +115,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
{ {
RequestType = OpenIdConnectRequestType.AuthenticationRequest RequestType = OpenIdConnectRequestType.AuthenticationRequest
}; };
var server = CreateServer(SetProtocolMessageOptions); var server = CreateServer(GetProtocolMessageOptions());
var transaction = await SendAsync(server, DefaultHost + Challenge); var transaction = await SendAsync(server, DefaultHost + Challenge);
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
queryValues.CheckValues(transaction.Response.Headers.Location.AbsoluteUri, new string[] {}); queryValues.CheckValues(transaction.Response.Headers.Location.AbsoluteUri, new string[] {});
@ -143,14 +137,15 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
{ {
RequestType = OpenIdConnectRequestType.LogoutRequest RequestType = OpenIdConnectRequestType.LogoutRequest
}; };
var server = CreateServer(SetProtocolMessageOptions); var server = CreateServer(GetProtocolMessageOptions());
var transaction = await SendAsync(server, DefaultHost + Signout); var transaction = await SendAsync(server, DefaultHost + Signout);
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
queryValues.CheckValues(transaction.Response.Headers.Location.AbsoluteUri, new string[] { }); queryValues.CheckValues(transaction.Response.Headers.Location.AbsoluteUri, new string[] { });
} }
private static void SetProtocolMessageOptions(OpenIdConnectOptions options) private static OpenIdConnectOptions GetProtocolMessageOptions()
{ {
var options = new OpenIdConnectOptions();
var fakeOpenIdRequestMessage = new FakeOpenIdConnectMessage(ExpectedAuthorizeRequest, ExpectedLogoutRequest); var fakeOpenIdRequestMessage = new FakeOpenIdConnectMessage(ExpectedAuthorizeRequest, ExpectedLogoutRequest);
options.AutomaticChallenge = true; options.AutomaticChallenge = true;
options.Events = new OpenIdConnectEvents() options.Events = new OpenIdConnectEvents()
@ -166,7 +161,9 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
return Task.FromResult(0); return Task.FromResult(0);
} }
}; };
return options;
} }
private class FakeOpenIdConnectMessage : OpenIdConnectMessage private class FakeOpenIdConnectMessage : OpenIdConnectMessage
{ {
private readonly string _authorizeRequest; private readonly string _authorizeRequest;
@ -207,21 +204,19 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
properties.Items.Add("item1", Guid.NewGuid().ToString()); properties.Items.Add("item1", Guid.NewGuid().ToString());
} }
var server = CreateServer(options => var options = GetOptions(DefaultParameters(new string[] { OpenIdConnectParameterNames.State }), queryValues, stateDataFormat);
options.AutomaticChallenge = challenge.Equals(ChallengeWithOutContext);
options.Events = new OpenIdConnectEvents()
{ {
SetOptions(options, DefaultParameters(new string[] { OpenIdConnectParameterNames.State }), queryValues, stateDataFormat); OnRedirectToAuthenticationEndpoint = context =>
options.AutomaticChallenge = challenge.Equals(ChallengeWithOutContext);
options.Events = new OpenIdConnectEvents()
{ {
OnRedirectToAuthenticationEndpoint = context => context.ProtocolMessage.State = userState;
{ context.ProtocolMessage.RedirectUri = queryValues.RedirectUri;
context.ProtocolMessage.State = userState; return Task.FromResult<object>(null);
context.ProtocolMessage.RedirectUri = queryValues.RedirectUri; }
return Task.FromResult<object>(null);
}
}; };
}, null, properties); var server = CreateServer(options, null, properties);
var transaction = await SendAsync(server, DefaultHost + challenge); var transaction = await SendAsync(server, DefaultHost + challenge);
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
@ -260,29 +255,28 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
{ {
var queryValues = new ExpectedQueryValues(DefaultAuthority); var queryValues = new ExpectedQueryValues(DefaultAuthority);
var queryValuesSetInEvent = new ExpectedQueryValues(DefaultAuthority); var queryValuesSetInEvent = new ExpectedQueryValues(DefaultAuthority);
var server = CreateServer(options => var options = GetOptions(DefaultParameters(), queryValues);
options.Events = new OpenIdConnectEvents()
{ {
SetOptions(options, DefaultParameters(), queryValues); OnRedirectToAuthenticationEndpoint = context =>
options.Events = new OpenIdConnectEvents()
{ {
OnRedirectToAuthenticationEndpoint = context => context.ProtocolMessage.ClientId = queryValuesSetInEvent.ClientId;
{ context.ProtocolMessage.RedirectUri = queryValuesSetInEvent.RedirectUri;
context.ProtocolMessage.ClientId = queryValuesSetInEvent.ClientId; context.ProtocolMessage.Resource = queryValuesSetInEvent.Resource;
context.ProtocolMessage.RedirectUri = queryValuesSetInEvent.RedirectUri; context.ProtocolMessage.Scope = queryValuesSetInEvent.Scope;
context.ProtocolMessage.Resource = queryValuesSetInEvent.Resource; return Task.FromResult<object>(null);
context.ProtocolMessage.Scope = queryValuesSetInEvent.Scope; }
return Task.FromResult<object>(null); };
} var server = CreateServer(options);
};
});
var transaction = await SendAsync(server, DefaultHost + Challenge); var transaction = await SendAsync(server, DefaultHost + Challenge);
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
queryValuesSetInEvent.CheckValues(transaction.Response.Headers.Location.AbsoluteUri, DefaultParameters()); queryValuesSetInEvent.CheckValues(transaction.Response.Headers.Location.AbsoluteUri, DefaultParameters());
} }
private void SetOptions(OpenIdConnectOptions options, List<string> parameters, ExpectedQueryValues queryValues, ISecureDataFormat<AuthenticationProperties> secureDataFormat = null) private OpenIdConnectOptions GetOptions(List<string> parameters, ExpectedQueryValues queryValues, ISecureDataFormat<AuthenticationProperties> secureDataFormat = null)
{ {
var options = new OpenIdConnectOptions();
foreach (var param in parameters) foreach (var param in parameters)
{ {
if (param.Equals(OpenIdConnectParameterNames.ClientId)) if (param.Equals(OpenIdConnectParameterNames.ClientId))
@ -301,6 +295,8 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
options.Authority = queryValues.Authority; options.Authority = queryValues.Authority;
options.Configuration = queryValues.Configuration; options.Configuration = queryValues.Configuration;
options.StateDataFormat = secureDataFormat ?? new AuthenticationPropertiesFormaterKeyValue(); options.StateDataFormat = secureDataFormat ?? new AuthenticationPropertiesFormaterKeyValue();
return options;
} }
private List<string> DefaultParameters(string[] additionalParams = null) private List<string> DefaultParameters(string[] additionalParams = null)
@ -333,11 +329,11 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
public async Task SignOutWithDefaultRedirectUri() public async Task SignOutWithDefaultRedirectUri()
{ {
var configuration = TestUtilities.DefaultOpenIdConnectConfiguration; var configuration = TestUtilities.DefaultOpenIdConnectConfiguration;
var server = CreateServer(options => var server = CreateServer(new OpenIdConnectOptions
{ {
options.Authority = DefaultAuthority; Authority = DefaultAuthority,
options.ClientId = "Test Id"; ClientId = "Test Id",
options.Configuration = configuration; Configuration = configuration
}); });
var transaction = await SendAsync(server, DefaultHost + Signout); var transaction = await SendAsync(server, DefaultHost + Signout);
@ -349,12 +345,12 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
public async Task SignOutWithCustomRedirectUri() public async Task SignOutWithCustomRedirectUri()
{ {
var configuration = TestUtilities.DefaultOpenIdConnectConfiguration; var configuration = TestUtilities.DefaultOpenIdConnectConfiguration;
var server = CreateServer(options => var server = CreateServer(new OpenIdConnectOptions
{ {
options.Authority = DefaultAuthority; Authority = DefaultAuthority,
options.ClientId = "Test Id"; ClientId = "Test Id",
options.Configuration = configuration; Configuration = configuration,
options.PostLogoutRedirectUri = "https://example.com/logout"; PostLogoutRedirectUri = "https://example.com/logout"
}); });
var transaction = await SendAsync(server, DefaultHost + Signout); var transaction = await SendAsync(server, DefaultHost + Signout);
@ -366,12 +362,12 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
public async Task SignOutWith_Specific_RedirectUri_From_Authentication_Properites() public async Task SignOutWith_Specific_RedirectUri_From_Authentication_Properites()
{ {
var configuration = TestUtilities.DefaultOpenIdConnectConfiguration; var configuration = TestUtilities.DefaultOpenIdConnectConfiguration;
var server = CreateServer(options => var server = CreateServer(new OpenIdConnectOptions
{ {
options.Authority = DefaultAuthority; Authority = DefaultAuthority,
options.ClientId = "Test Id"; ClientId = "Test Id",
options.Configuration = configuration; Configuration = configuration,
options.PostLogoutRedirectUri = "https://example.com/logout"; PostLogoutRedirectUri = "https://example.com/logout"
}); });
var transaction = await SendAsync(server, "https://example.com/signout_with_specific_redirect_uri"); var transaction = await SendAsync(server, "https://example.com/signout_with_specific_redirect_uri");
@ -379,16 +375,16 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
Assert.Contains(UrlEncoder.Default.Encode("http://www.example.com/specific_redirect_uri"), transaction.Response.Headers.Location.AbsoluteUri); Assert.Contains(UrlEncoder.Default.Encode("http://www.example.com/specific_redirect_uri"), transaction.Response.Headers.Location.AbsoluteUri);
} }
private static TestServer CreateServer(Action<OpenIdConnectOptions> configureOptions, Func<HttpContext, Task> handler = null, AuthenticationProperties properties = null) private static TestServer CreateServer(OpenIdConnectOptions options, Func<HttpContext, Task> handler = null, AuthenticationProperties properties = null)
{ {
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => app.UseCookieAuthentication(new CookieAuthenticationOptions
{ {
options.AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme; AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme
}); });
app.UseOpenIdConnectAuthentication(configureOptions); app.UseOpenIdConnectAuthentication(options);
app.Use(async (context, next) => app.Use(async (context, next) =>
{ {
var req = context.Request; var req = context.Request;
@ -434,9 +430,9 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
.ConfigureServices(services => .ConfigureServices(services =>
{ {
services.AddAuthentication(); services.AddAuthentication();
services.Configure<SharedAuthenticationOptions>(options => services.Configure<SharedAuthenticationOptions>(authOptions =>
{ {
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; authOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}); });
}); });
return new TestServer(builder); return new TestServer(builder);

View File

@ -20,19 +20,19 @@ namespace Microsoft.AspNet.Authentication.Twitter
[Fact] [Fact]
public async Task ChallengeWillTriggerApplyRedirectEvent() public async Task ChallengeWillTriggerApplyRedirectEvent()
{ {
var server = CreateServer(options => var server = CreateServer(new TwitterOptions
{ {
options.ConsumerKey = "Test Consumer Key"; ConsumerKey = "Test Consumer Key",
options.ConsumerSecret = "Test Consumer Secret"; ConsumerSecret = "Test Consumer Secret",
options.Events = new TwitterEvents Events = new TwitterEvents
{ {
OnRedirectToAuthorizationEndpoint = context => OnRedirectToAuthorizationEndpoint = context =>
{ {
context.Response.Redirect(context.RedirectUri + "&custom=test"); context.Response.Redirect(context.RedirectUri + "&custom=test");
return Task.FromResult(0); return Task.FromResult(0);
} }
}; },
options.BackchannelHttpHandler = new TestHttpMessageHandler BackchannelHttpHandler = new TestHttpMessageHandler
{ {
Sender = req => Sender = req =>
{ {
@ -48,7 +48,7 @@ namespace Microsoft.AspNet.Authentication.Twitter
} }
return null; return null;
} }
}; }
}, },
context => context =>
{ {
@ -65,10 +65,10 @@ namespace Microsoft.AspNet.Authentication.Twitter
[Fact] [Fact]
public async Task BadSignInWillThrow() public async Task BadSignInWillThrow()
{ {
var server = CreateServer(options => var server = CreateServer(new TwitterOptions
{ {
options.ConsumerKey = "Test Consumer Key"; ConsumerKey = "Test Consumer Key",
options.ConsumerSecret = "Test Consumer Secret"; ConsumerSecret = "Test Consumer Secret"
}); });
// Send a bogus sign in // Send a bogus sign in
@ -79,10 +79,10 @@ namespace Microsoft.AspNet.Authentication.Twitter
[Fact] [Fact]
public async Task SignInThrows() public async Task SignInThrows()
{ {
var server = CreateServer(options => var server = CreateServer(new TwitterOptions
{ {
options.ConsumerKey = "Test Consumer Key"; ConsumerKey = "Test Consumer Key",
options.ConsumerSecret = "Test Consumer Secret"; ConsumerSecret = "Test Consumer Secret"
}); });
var transaction = await server.SendAsync("https://example.com/signIn"); var transaction = await server.SendAsync("https://example.com/signIn");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -91,10 +91,10 @@ namespace Microsoft.AspNet.Authentication.Twitter
[Fact] [Fact]
public async Task SignOutThrows() public async Task SignOutThrows()
{ {
var server = CreateServer(options => var server = CreateServer(new TwitterOptions
{ {
options.ConsumerKey = "Test Consumer Key"; ConsumerKey = "Test Consumer Key",
options.ConsumerSecret = "Test Consumer Secret"; ConsumerSecret = "Test Consumer Secret"
}); });
var transaction = await server.SendAsync("https://example.com/signOut"); var transaction = await server.SendAsync("https://example.com/signOut");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -103,10 +103,10 @@ namespace Microsoft.AspNet.Authentication.Twitter
[Fact] [Fact]
public async Task ForbidThrows() public async Task ForbidThrows()
{ {
var server = CreateServer(options => var server = CreateServer(new TwitterOptions
{ {
options.ConsumerKey = "Test Consumer Key"; ConsumerKey = "Test Consumer Key",
options.ConsumerSecret = "Test Consumer Secret"; ConsumerSecret = "Test Consumer Secret"
}); });
var transaction = await server.SendAsync("https://example.com/signOut"); var transaction = await server.SendAsync("https://example.com/signOut");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
@ -116,11 +116,11 @@ namespace Microsoft.AspNet.Authentication.Twitter
[Fact] [Fact]
public async Task ChallengeWillTriggerRedirection() public async Task ChallengeWillTriggerRedirection()
{ {
var server = CreateServer(options => var server = CreateServer(new TwitterOptions
{ {
options.ConsumerKey = "Test Consumer Key"; ConsumerKey = "Test Consumer Key",
options.ConsumerSecret = "Test Consumer Secret"; ConsumerSecret = "Test Consumer Secret",
options.BackchannelHttpHandler = new TestHttpMessageHandler BackchannelHttpHandler = new TestHttpMessageHandler
{ {
Sender = req => Sender = req =>
{ {
@ -136,7 +136,7 @@ namespace Microsoft.AspNet.Authentication.Twitter
} }
return null; return null;
} }
}; }
}, },
context => context =>
{ {
@ -150,16 +150,16 @@ namespace Microsoft.AspNet.Authentication.Twitter
Assert.Contains("https://api.twitter.com/oauth/authenticate?oauth_token=", location); Assert.Contains("https://api.twitter.com/oauth/authenticate?oauth_token=", location);
} }
private static TestServer CreateServer(Action<TwitterOptions> configure, Func<HttpContext, bool> handler = null) private static TestServer CreateServer(TwitterOptions options, Func<HttpContext, bool> handler = null)
{ {
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => app.UseCookieAuthentication(new CookieAuthenticationOptions
{ {
options.AuthenticationScheme = "External"; AuthenticationScheme = "External"
}); });
app.UseTwitterAuthentication(configure); app.UseTwitterAuthentication(options);
app.Use(async (context, next) => app.Use(async (context, next) =>
{ {
var req = context.Request; var req = context.Request;
@ -185,9 +185,9 @@ namespace Microsoft.AspNet.Authentication.Twitter
.ConfigureServices(services => .ConfigureServices(services =>
{ {
services.AddAuthentication(); services.AddAuthentication();
services.Configure<SharedAuthenticationOptions>(options => services.Configure<SharedAuthenticationOptions>(authOptions =>
{ {
options.SignInScheme = "External"; authOptions.SignInScheme = "External";
}); });
}); });
return new TestServer(builder); return new TestServer(builder);

View File

@ -19,6 +19,7 @@ namespace Microsoft.AspNet.Authorization.Test
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddAuthorization(); services.AddAuthorization();
services.AddLogging(); services.AddLogging();
services.AddOptions();
if (setupServices != null) if (setupServices != null)
{ {
setupServices(services); setupServices(services);

View File

@ -36,7 +36,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test
public async Task SecureAlwaysSetsSecure() public async Task SecureAlwaysSetsSecure()
{ {
await RunTest("/secureAlways", await RunTest("/secureAlways",
options => options.Secure = SecurePolicy.Always, new CookiePolicyOptions
{
Secure = SecurePolicy.Always
},
SecureCookieAppends, SecureCookieAppends,
new RequestTest("http://example.com/secureAlways", new RequestTest("http://example.com/secureAlways",
transaction => transaction =>
@ -53,7 +56,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test
public async Task SecureNoneLeavesSecureUnchanged() public async Task SecureNoneLeavesSecureUnchanged()
{ {
await RunTest("/secureNone", await RunTest("/secureNone",
options => options.Secure = SecurePolicy.None, new CookiePolicyOptions
{
Secure = SecurePolicy.None
},
SecureCookieAppends, SecureCookieAppends,
new RequestTest("http://example.com/secureNone", new RequestTest("http://example.com/secureNone",
transaction => transaction =>
@ -71,7 +77,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test
public async Task SecureSameUsesRequest() public async Task SecureSameUsesRequest()
{ {
await RunTest("/secureSame", await RunTest("/secureSame",
options => options.Secure = SecurePolicy.SameAsRequest, new CookiePolicyOptions
{
Secure = SecurePolicy.SameAsRequest
},
SecureCookieAppends, SecureCookieAppends,
new RequestTest("http://example.com/secureSame", new RequestTest("http://example.com/secureSame",
transaction => transaction =>
@ -97,7 +106,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test
public async Task HttpOnlyAlwaysSetsItAlways() public async Task HttpOnlyAlwaysSetsItAlways()
{ {
await RunTest("/httpOnlyAlways", await RunTest("/httpOnlyAlways",
options => options.HttpOnly = HttpOnlyPolicy.Always, new CookiePolicyOptions
{
HttpOnly = HttpOnlyPolicy.Always
},
HttpCookieAppends, HttpCookieAppends,
new RequestTest("http://example.com/httpOnlyAlways", new RequestTest("http://example.com/httpOnlyAlways",
transaction => transaction =>
@ -114,7 +126,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test
public async Task HttpOnlyNoneLeavesItAlone() public async Task HttpOnlyNoneLeavesItAlone()
{ {
await RunTest("/httpOnlyNone", await RunTest("/httpOnlyNone",
options => options.HttpOnly = HttpOnlyPolicy.None, new CookiePolicyOptions
{
HttpOnly = HttpOnlyPolicy.None
},
HttpCookieAppends, HttpCookieAppends,
new RequestTest("http://example.com/httpOnlyNone", new RequestTest("http://example.com/httpOnlyNone",
transaction => transaction =>
@ -133,7 +148,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookiePolicy(options => options.OnAppendCookie = ctx => ctx.CookieName = ctx.CookieValue = "Hao"); app.UseCookiePolicy(new CookiePolicyOptions
{
OnAppendCookie = ctx => ctx.CookieName = ctx.CookieValue = "Hao"
});
app.Run(context => app.Run(context =>
{ {
context.Response.Cookies.Append("A", "A"); context.Response.Cookies.Append("A", "A");
@ -160,7 +178,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookiePolicy(options => options.OnDeleteCookie = ctx => ctx.CookieName = "A"); app.UseCookiePolicy(new CookiePolicyOptions
{
OnDeleteCookie = ctx => ctx.CookieName = "A"
});
app.Run(context => app.Run(context =>
{ {
context.Response.Cookies.Delete("A"); context.Response.Cookies.Delete("A");
@ -190,7 +211,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test
context.Features.Set<IResponseCookiesFeature>(new TestCookieFeature()); context.Features.Set<IResponseCookiesFeature>(new TestCookieFeature());
return next(context); return next(context);
}); });
app.UseCookiePolicy(options => options.OnDeleteCookie = ctx => ctx.CookieName = "A"); app.UseCookiePolicy(new CookiePolicyOptions
{
OnDeleteCookie = ctx => ctx.CookieName = "A"
});
app.Run(context => app.Run(context =>
{ {
Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Delete("A")); Assert.Throws<NotImplementedException>(() => context.Response.Cookies.Delete("A"));
@ -254,7 +278,7 @@ namespace Microsoft.AspNet.CookiePolicy.Test
private async Task RunTest( private async Task RunTest(
string path, string path,
Action<CookiePolicyOptions> configureCookiePolicy, CookiePolicyOptions cookiePolicy,
RequestDelegate configureSetup, RequestDelegate configureSetup,
params RequestTest[] tests) params RequestTest[] tests)
{ {
@ -263,7 +287,7 @@ namespace Microsoft.AspNet.CookiePolicy.Test
{ {
app.Map(path, map => app.Map(path, map =>
{ {
map.UseCookiePolicy(configureCookiePolicy); map.UseCookiePolicy(cookiePolicy);
map.Run(configureSetup); map.Run(configureSetup);
}); });
}); });

View File

@ -38,7 +38,7 @@ namespace Microsoft.Owin.Security.Interop
{ {
app.Properties["host.AppName"] = "Microsoft.Owin.Security.Tests"; app.Properties["host.AppName"] = "Microsoft.Owin.Security.Tests";
app.UseCookieAuthentication(new CookieAuthenticationOptions app.UseCookieAuthentication(new Cookies.CookieAuthenticationOptions
{ {
TicketDataFormat = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector)) TicketDataFormat = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector))
}); });
@ -55,7 +55,10 @@ namespace Microsoft.Owin.Security.Interop
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => options.DataProtectionProvider = dataProtection); app.UseCookieAuthentication(new AspNet.Builder.CookieAuthenticationOptions
{
DataProtectionProvider = dataProtection
});
app.Run(async context => app.Run(async context =>
{ {
var result = await context.Authentication.AuthenticateAsync("Cookies"); var result = await context.Authentication.AuthenticateAsync("Cookies");
@ -88,7 +91,10 @@ namespace Microsoft.Owin.Security.Interop
var builder = new WebApplicationBuilder() var builder = new WebApplicationBuilder()
.Configure(app => .Configure(app =>
{ {
app.UseCookieAuthentication(options => options.DataProtectionProvider = dataProtection); app.UseCookieAuthentication(new AspNet.Builder.CookieAuthenticationOptions
{
DataProtectionProvider = dataProtection
});
app.Run(context => context.Authentication.SignInAsync("Cookies", user)); app.Run(context => context.Authentication.SignInAsync("Cookies", user));
}) })
.ConfigureServices(services => services.AddAuthentication()); .ConfigureServices(services => services.AddAuthentication());
@ -100,7 +106,7 @@ namespace Microsoft.Owin.Security.Interop
{ {
app.Properties["host.AppName"] = "Microsoft.Owin.Security.Tests"; app.Properties["host.AppName"] = "Microsoft.Owin.Security.Tests";
app.UseCookieAuthentication(new CookieAuthenticationOptions app.UseCookieAuthentication(new Owin.Security.Cookies.CookieAuthenticationOptions
{ {
TicketDataFormat = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector)) TicketDataFormat = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector))
}); });