diff --git a/samples/CookieSample/Startup.cs b/samples/CookieSample/Startup.cs index dca9105128..b3327ac81c 100644 --- a/samples/CookieSample/Startup.cs +++ b/samples/CookieSample/Startup.cs @@ -20,9 +20,9 @@ namespace CookieSample { loggerfactory.AddConsole(LogLevel.Information); - app.UseCookieAuthentication(options => + app.UseCookieAuthentication(new CookieAuthenticationOptions { - options.AutomaticAuthenticate = true; + AutomaticAuthenticate = true }); app.Run(async context => diff --git a/samples/CookieSessionSample/Startup.cs b/samples/CookieSessionSample/Startup.cs index bf7200ca6a..6160f56b95 100644 --- a/samples/CookieSessionSample/Startup.cs +++ b/samples/CookieSessionSample/Startup.cs @@ -21,10 +21,10 @@ namespace CookieSessionSample { loggerfactory.AddConsole(LogLevel.Information); - app.UseCookieAuthentication(options => + app.UseCookieAuthentication(new CookieAuthenticationOptions { - options.AutomaticAuthenticate = true; - options.SessionStore = new MemoryCacheTicketStore(); + AutomaticAuthenticate = true, + SessionStore = new MemoryCacheTicketStore() }); app.Run(async context => diff --git a/samples/JwtBearerSample/Startup.cs b/samples/JwtBearerSample/Startup.cs index 88032b8e69..db91629bcf 100644 --- a/samples/JwtBearerSample/Startup.cs +++ b/samples/JwtBearerSample/Startup.cs @@ -59,13 +59,13 @@ namespace JwtBearerSample app.UseDefaultFiles(); app.UseStaticFiles(); - app.UseJwtBearerAuthentication(options => + app.UseJwtBearerAuthentication(new JwtBearerOptions { - options.AutomaticAuthenticate = true; - options.AutomaticChallenge = true; + AutomaticAuthenticate = true, + AutomaticChallenge = true, // You also need to update /wwwroot/app/scripts/app.js - options.Authority = Configuration["jwt:authority"]; - options.Audience = Configuration["jwt:audience"]; + Authority = Configuration["jwt:authority"], + Audience = Configuration["jwt:audience"] }); // [Authorize] would usually handle this diff --git a/samples/OpenIdConnectSample/Startup.cs b/samples/OpenIdConnectSample/Startup.cs index 67a979ea91..bf4a4bc759 100644 --- a/samples/OpenIdConnectSample/Startup.cs +++ b/samples/OpenIdConnectSample/Startup.cs @@ -35,18 +35,18 @@ namespace OpenIdConnectSample 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"]; - options.ClientSecret = Configuration["oidc:clientsecret"]; // for code flow - options.Authority = Configuration["oidc:authority"]; - options.ResponseType = OpenIdConnectResponseTypes.Code; - options.GetClaimsFromUserInfoEndpoint = true; + ClientId = Configuration["oidc:clientid"], + ClientSecret = Configuration["oidc:clientsecret"], // for code flow + Authority = Configuration["oidc:authority"], + ResponseType = OpenIdConnectResponseTypes.Code, + GetClaimsFromUserInfoEndpoint = true }); app.Run(async context => diff --git a/samples/SocialSample/Startup.cs b/samples/SocialSample/Startup.cs index f1bc5b335f..65067ada8e 100644 --- a/samples/SocialSample/Startup.cs +++ b/samples/SocialSample/Startup.cs @@ -63,47 +63,44 @@ namespace CookieSample } }); - app.UseCookieAuthentication(options => + app.UseCookieAuthentication(new CookieAuthenticationOptions { - options.AutomaticAuthenticate = true; - options.AutomaticChallenge = true; - options.LoginPath = new PathString("/login"); + AutomaticAuthenticate = true, + AutomaticChallenge = true, + 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. // https://developers.facebook.com/apps/ - app.UseFacebookAuthentication(options => + app.UseFacebookAuthentication(new FacebookOptions { - options.AppId = Configuration["facebook:appid"]; - options.AppSecret = Configuration["facebook:appsecret"]; - options.Scope.Add("email"); - options.Fields.Add("name"); - options.Fields.Add("email"); + AppId = Configuration["facebook:appid"], + AppSecret = Configuration["facebook:appsecret"], + Scope = { "email" }, + Fields = { "name", "email" } }); // See config.json - app.UseOAuthAuthentication(options => + app.UseOAuthAuthentication(new OAuthOptions { - options.AuthenticationScheme = "Google-AccessToken"; - options.DisplayName = "Google-AccessToken"; - options.ClientId = Configuration["google:clientid"]; - options.ClientSecret = Configuration["google:clientsecret"]; - options.CallbackPath = new PathString("/signin-google-token"); - options.AuthorizationEndpoint = GoogleDefaults.AuthorizationEndpoint; - options.TokenEndpoint = GoogleDefaults.TokenEndpoint; - options.Scope.Add("openid"); - options.Scope.Add("profile"); - options.Scope.Add("email"); - options.SaveTokensAsClaims = true; + AuthenticationScheme = "Google-AccessToken", + DisplayName = "Google-AccessToken", + ClientId = Configuration["google:clientid"], + ClientSecret = Configuration["google:clientsecret"], + CallbackPath = new PathString("/signin-google-token"), + AuthorizationEndpoint = GoogleDefaults.AuthorizationEndpoint, + TokenEndpoint = GoogleDefaults.TokenEndpoint, + Scope = { "openid", "profile", "email" }, + SaveTokensAsClaims = true }); // See config.json // https://console.developers.google.com/project - app.UseGoogleAuthentication(options => + app.UseGoogleAuthentication(new GoogleOptions { - options.ClientId = Configuration["google:clientid"]; - options.ClientSecret = Configuration["google:clientsecret"]; - options.Events = new OAuthEvents() + ClientId = Configuration["google:clientid"], + ClientSecret = Configuration["google:clientsecret"], + Events = new OAuthEvents() { OnRemoteFailure = ctx => @@ -112,17 +109,16 @@ namespace CookieSample ctx.HandleResponse(); return Task.FromResult(0); } - }; - + } }); // See config.json // https://apps.twitter.com/ - app.UseTwitterAuthentication(options => + app.UseTwitterAuthentication(new TwitterOptions { - options.ConsumerKey = Configuration["twitter:consumerkey"]; - options.ConsumerSecret = Configuration["twitter:consumersecret"]; - options.Events = new TwitterEvents() + ConsumerKey = Configuration["twitter:consumerkey"], + ConsumerSecret = Configuration["twitter:consumersecret"], + Events = new TwitterEvents() { OnRemoteFailure = ctx => { @@ -130,7 +126,7 @@ namespace CookieSample ctx.HandleResponse(); 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. @@ -151,56 +147,56 @@ namespace CookieSample The sample app can then be run via: dnx . web */ - app.UseOAuthAuthentication(options => + app.UseOAuthAuthentication(new OAuthOptions { - options.AuthenticationScheme = "Microsoft-AccessToken"; - options.DisplayName = "MicrosoftAccount-AccessToken - Requires project changes"; - options.ClientId = Configuration["msa:clientid"]; - options.ClientSecret = Configuration["msa:clientsecret"]; - options.CallbackPath = new PathString("/signin-microsoft-token"); - options.AuthorizationEndpoint = MicrosoftAccountDefaults.AuthorizationEndpoint; - options.TokenEndpoint = MicrosoftAccountDefaults.TokenEndpoint; - options.Scope.Add("wl.basic"); - options.SaveTokensAsClaims = true; + AuthenticationScheme = "Microsoft-AccessToken", + DisplayName = "MicrosoftAccount-AccessToken - Requires project changes", + ClientId = Configuration["msa:clientid"], + ClientSecret = Configuration["msa:clientsecret"], + CallbackPath = new PathString("/signin-microsoft-token"), + AuthorizationEndpoint = MicrosoftAccountDefaults.AuthorizationEndpoint, + TokenEndpoint = MicrosoftAccountDefaults.TokenEndpoint, + Scope = { "wl.basic" }, + 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. - app.UseMicrosoftAccountAuthentication(options => + app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions { - options.DisplayName = "MicrosoftAccount - Requires project changes"; - options.ClientId = Configuration["msa:clientid"]; - options.ClientSecret = Configuration["msa:clientsecret"]; - options.Scope.Add("wl.emails"); + DisplayName = "MicrosoftAccount - Requires project changes", + ClientId = Configuration["msa:clientid"], + ClientSecret = Configuration["msa:clientsecret"], + Scope = { "wl.emails" } }); // See config.json // https://github.com/settings/applications/ - app.UseOAuthAuthentication(options => + app.UseOAuthAuthentication(new OAuthOptions { - options.AuthenticationScheme = "GitHub-AccessToken"; - options.DisplayName = "Github-AccessToken"; - options.ClientId = Configuration["github-token:clientid"]; - options.ClientSecret = Configuration["github-token:clientsecret"]; - options.CallbackPath = new PathString("/signin-github-token"); - options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize"; - options.TokenEndpoint = "https://github.com/login/oauth/access_token"; - options.SaveTokensAsClaims = true; + AuthenticationScheme = "GitHub-AccessToken", + DisplayName = "Github-AccessToken", + ClientId = Configuration["github-token:clientid"], + ClientSecret = Configuration["github-token:clientsecret"], + CallbackPath = new PathString("/signin-github-token"), + AuthorizationEndpoint = "https://github.com/login/oauth/authorize", + TokenEndpoint = "https://github.com/login/oauth/access_token", + SaveTokensAsClaims = true }); // See config.json - app.UseOAuthAuthentication(options => + app.UseOAuthAuthentication(new OAuthOptions { - options.AuthenticationScheme = "GitHub"; - options.DisplayName = "Github"; - options.ClientId = Configuration["github:clientid"]; - options.ClientSecret = Configuration["github:clientsecret"]; - options.CallbackPath = new PathString("/signin-github"); - options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize"; - options.TokenEndpoint = "https://github.com/login/oauth/access_token"; - options.UserInformationEndpoint = "https://api.github.com/user"; - options.ClaimsIssuer = "OAuth2-Github"; + AuthenticationScheme = "GitHub", + DisplayName = "Github", + ClientId = Configuration["github:clientid"], + ClientSecret = Configuration["github:clientsecret"], + CallbackPath = new PathString("/signin-github"), + AuthorizationEndpoint = "https://github.com/login/oauth/authorize", + TokenEndpoint = "https://github.com/login/oauth/access_token", + UserInformationEndpoint = "https://api.github.com/user", + ClaimsIssuer = "OAuth2-Github", // Retrieving user information is unique to each provider. - options.Events = new OAuthEvents + Events = new OAuthEvents { OnCreatingTicket = async context => { @@ -246,7 +242,7 @@ namespace CookieSample ClaimValueTypes.String, context.Options.ClaimsIssuer)); } } - }; + } }); // Choose an authentication type diff --git a/src/Microsoft.AspNet.Authentication.Cookies/CookieAppBuilderExtensions.cs b/src/Microsoft.AspNet.Authentication.Cookies/CookieAppBuilderExtensions.cs index f990df58aa..8582648877 100644 --- a/src/Microsoft.AspNet.Authentication.Cookies/CookieAppBuilderExtensions.cs +++ b/src/Microsoft.AspNet.Authentication.Cookies/CookieAppBuilderExtensions.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNet.Authentication.Cookies; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Builder { @@ -22,31 +23,8 @@ namespace Microsoft.AspNet.Builder { throw new ArgumentNullException(nameof(app)); } - - return app.UseCookieAuthentication(options => { }); - } - - /// - /// Adds the middleware to the specified , which enables cookie authentication capabilities. - /// - /// The to add the middleware to. - /// An action delegate to configure the provided . - /// A reference to this instance after the operation has completed. - public static IApplicationBuilder UseCookieAuthentication(this IApplicationBuilder app, Action 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(options); + + return app.UseMiddleware(); } /// @@ -66,7 +44,7 @@ namespace Microsoft.AspNet.Builder throw new ArgumentNullException(nameof(options)); } - return app.UseMiddleware(options); + return app.UseMiddleware(Options.Create(options)); } } } \ No newline at end of file diff --git a/src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationHandler.cs b/src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationHandler.cs index 82a47ecaeb..040539d4d9 100644 --- a/src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationHandler.cs +++ b/src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationHandler.cs @@ -6,6 +6,7 @@ using System; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Features; diff --git a/src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationMiddleware.cs b/src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationMiddleware.cs index 9ec4064843..c15b10d345 100644 --- a/src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationMiddleware.cs +++ b/src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationMiddleware.cs @@ -3,9 +3,11 @@ using System; using System.Text.Encodings.Web; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.Http; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Authentication.Cookies { @@ -16,34 +18,14 @@ namespace Microsoft.AspNet.Authentication.Cookies IDataProtectionProvider dataProtectionProvider, ILoggerFactory loggerFactory, UrlEncoder urlEncoder, - CookieAuthenticationOptions options) + IOptions options) : base(next, options, loggerFactory, urlEncoder) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - if (dataProtectionProvider == null) { 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) { Options.Events = new CookieAuthenticationEvents(); diff --git a/src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationOptions.cs b/src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationOptions.cs index 830b559c96..075353887f 100644 --- a/src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationOptions.cs +++ b/src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationOptions.cs @@ -4,11 +4,13 @@ using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNet.Authentication; +using Microsoft.AspNet.Authentication.Cookies; using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.Http; using Microsoft.Extensions.Options; -namespace Microsoft.AspNet.Authentication.Cookies +namespace Microsoft.AspNet.Builder { /// /// Contains the options used by the CookiesAuthenticationMiddleware diff --git a/src/Microsoft.AspNet.Authentication.Cookies/Events/BaseCookieContext.cs b/src/Microsoft.AspNet.Authentication.Cookies/Events/BaseCookieContext.cs index 6a437551fe..d3e9127eed 100644 --- a/src/Microsoft.AspNet.Authentication.Cookies/Events/BaseCookieContext.cs +++ b/src/Microsoft.AspNet.Authentication.Cookies/Events/BaseCookieContext.cs @@ -2,9 +2,8 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Security.Claims; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; -using Microsoft.AspNet.Http.Authentication; namespace Microsoft.AspNet.Authentication.Cookies { diff --git a/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieRedirectContext.cs b/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieRedirectContext.cs index 437e8927e1..4f0266b855 100644 --- a/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieRedirectContext.cs +++ b/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieRedirectContext.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; diff --git a/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieSignedInContext.cs b/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieSignedInContext.cs index 17f5090cda..2412722c08 100644 --- a/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieSignedInContext.cs +++ b/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieSignedInContext.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Security.Claims; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; diff --git a/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieSigningInContext.cs b/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieSigningInContext.cs index fa441b4b0e..709549d0aa 100644 --- a/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieSigningInContext.cs +++ b/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieSigningInContext.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Security.Claims; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; diff --git a/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieSigningOutContext.cs b/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieSigningOutContext.cs index a510dbcb59..2de962ef4e 100644 --- a/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieSigningOutContext.cs +++ b/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieSigningOutContext.cs @@ -1,6 +1,7 @@ // 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; diff --git a/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieValidatePrincipalContext.cs b/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieValidatePrincipalContext.cs index af06533855..435499bf57 100644 --- a/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieValidatePrincipalContext.cs +++ b/src/Microsoft.AspNet.Authentication.Cookies/Events/CookieValidatePrincipalContext.cs @@ -3,6 +3,7 @@ using System; using System.Security.Claims; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; diff --git a/src/Microsoft.AspNet.Authentication.Cookies/project.json b/src/Microsoft.AspNet.Authentication.Cookies/project.json index b9b1d5d308..8a6fdac7be 100644 --- a/src/Microsoft.AspNet.Authentication.Cookies/project.json +++ b/src/Microsoft.AspNet.Authentication.Cookies/project.json @@ -11,6 +11,7 @@ }, "dependencies": { "Microsoft.AspNet.Authentication": "1.0.0-*", + "Microsoft.Extensions.Options": "1.0.0-*", "Microsoft.Extensions.WebEncoders": "1.0.0-*", "Newtonsoft.Json": "6.0.6" }, diff --git a/src/Microsoft.AspNet.Authentication.Facebook/FacebookAppBuilderExtensions.cs b/src/Microsoft.AspNet.Authentication.Facebook/FacebookAppBuilderExtensions.cs index f649790a1a..19ff8fa67e 100644 --- a/src/Microsoft.AspNet.Authentication.Facebook/FacebookAppBuilderExtensions.cs +++ b/src/Microsoft.AspNet.Authentication.Facebook/FacebookAppBuilderExtensions.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNet.Authentication.Facebook; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Builder { @@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder /// Adds the middleware to the specified , which enables Facebook authentication capabilities. /// /// The to add the middleware to. - /// An action delegate to configure the provided . /// A reference to this instance after the operation has completed. - public static IApplicationBuilder UseFacebookAuthentication(this IApplicationBuilder app, Action configureOptions) + public static IApplicationBuilder UseFacebookAuthentication(this IApplicationBuilder app) { if (app == null) { throw new ArgumentNullException(nameof(app)); } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - var options = new FacebookOptions(); - configureOptions(options); - - return app.UseMiddleware(options); + return app.UseMiddleware(); } /// @@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder throw new ArgumentNullException(nameof(options)); } - return app.UseMiddleware(options); + return app.UseMiddleware(Options.Create(options)); } } } diff --git a/src/Microsoft.AspNet.Authentication.Facebook/FacebookHandler.cs b/src/Microsoft.AspNet.Authentication.Facebook/FacebookHandler.cs index 44bc1468ee..7c74b253f3 100644 --- a/src/Microsoft.AspNet.Authentication.Facebook/FacebookHandler.cs +++ b/src/Microsoft.AspNet.Authentication.Facebook/FacebookHandler.cs @@ -8,6 +8,7 @@ using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Microsoft.AspNet.Authentication.OAuth; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.WebUtilities; using Newtonsoft.Json.Linq; diff --git a/src/Microsoft.AspNet.Authentication.Facebook/FacebookMiddleware.cs b/src/Microsoft.AspNet.Authentication.Facebook/FacebookMiddleware.cs index 441145681d..f6d04171a9 100644 --- a/src/Microsoft.AspNet.Authentication.Facebook/FacebookMiddleware.cs +++ b/src/Microsoft.AspNet.Authentication.Facebook/FacebookMiddleware.cs @@ -5,6 +5,7 @@ using System; using System.Globalization; using System.Text.Encodings.Web; using Microsoft.AspNet.Authentication.OAuth; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.Http; using Microsoft.Extensions.Logging; @@ -33,7 +34,7 @@ namespace Microsoft.AspNet.Authentication.Facebook ILoggerFactory loggerFactory, UrlEncoder encoder, IOptions sharedOptions, - FacebookOptions options) + IOptions options) : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options) { if (next == null) diff --git a/src/Microsoft.AspNet.Authentication.Facebook/FacebookOptions.cs b/src/Microsoft.AspNet.Authentication.Facebook/FacebookOptions.cs index b6ceb5f0f0..25e02cf778 100644 --- a/src/Microsoft.AspNet.Authentication.Facebook/FacebookOptions.cs +++ b/src/Microsoft.AspNet.Authentication.Facebook/FacebookOptions.cs @@ -2,10 +2,10 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; -using Microsoft.AspNet.Authentication.OAuth; +using Microsoft.AspNet.Authentication.Facebook; using Microsoft.AspNet.Http; -namespace Microsoft.AspNet.Authentication.Facebook +namespace Microsoft.AspNet.Builder { /// /// Configuration options for . diff --git a/src/Microsoft.AspNet.Authentication.Google/GoogleAppBuilderExtensions.cs b/src/Microsoft.AspNet.Authentication.Google/GoogleAppBuilderExtensions.cs index 34f65b112e..e380ebf475 100644 --- a/src/Microsoft.AspNet.Authentication.Google/GoogleAppBuilderExtensions.cs +++ b/src/Microsoft.AspNet.Authentication.Google/GoogleAppBuilderExtensions.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNet.Authentication.Google; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Builder { @@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder /// Adds the middleware to the specified , which enables Google authentication capabilities. /// /// The to add the middleware to. - /// An action delegate to configure the provided . /// A reference to this instance after the operation has completed. - public static IApplicationBuilder UseGoogleAuthentication(this IApplicationBuilder app, Action configureOptions) + public static IApplicationBuilder UseGoogleAuthentication(this IApplicationBuilder app) { if (app == null) { throw new ArgumentNullException(nameof(app)); } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - var options = new GoogleOptions(); - configureOptions(options); - - return app.UseMiddleware(options); + return app.UseMiddleware(); } /// @@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder throw new ArgumentNullException(nameof(options)); } - return app.UseMiddleware(options); + return app.UseMiddleware(Options.Create(options)); } } } diff --git a/src/Microsoft.AspNet.Authentication.Google/GoogleHandler.cs b/src/Microsoft.AspNet.Authentication.Google/GoogleHandler.cs index e4b50132ad..675e424422 100644 --- a/src/Microsoft.AspNet.Authentication.Google/GoogleHandler.cs +++ b/src/Microsoft.AspNet.Authentication.Google/GoogleHandler.cs @@ -7,8 +7,9 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Security.Claims; using System.Threading.Tasks; -using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Authentication.OAuth; +using Microsoft.AspNet.Builder; +using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.WebUtilities; using Newtonsoft.Json.Linq; diff --git a/src/Microsoft.AspNet.Authentication.Google/GoogleMiddleware.cs b/src/Microsoft.AspNet.Authentication.Google/GoogleMiddleware.cs index 55d2b0ed13..72ec3dee98 100644 --- a/src/Microsoft.AspNet.Authentication.Google/GoogleMiddleware.cs +++ b/src/Microsoft.AspNet.Authentication.Google/GoogleMiddleware.cs @@ -5,6 +5,7 @@ using System; using System.Diagnostics.CodeAnalysis; using System.Text.Encodings.Web; using Microsoft.AspNet.Authentication.OAuth; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.Http; using Microsoft.Extensions.Logging; @@ -34,7 +35,7 @@ namespace Microsoft.AspNet.Authentication.Google ILoggerFactory loggerFactory, UrlEncoder encoder, IOptions sharedOptions, - GoogleOptions options) + IOptions options) : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options) { if (next == null) diff --git a/src/Microsoft.AspNet.Authentication.Google/GoogleOptions.cs b/src/Microsoft.AspNet.Authentication.Google/GoogleOptions.cs index 2c00278c78..eb1f0c3f1b 100644 --- a/src/Microsoft.AspNet.Authentication.Google/GoogleOptions.cs +++ b/src/Microsoft.AspNet.Authentication.Google/GoogleOptions.cs @@ -1,10 +1,10 @@ // 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.Authentication.OAuth; +using Microsoft.AspNet.Authentication.Google; using Microsoft.AspNet.Http; -namespace Microsoft.AspNet.Authentication.Google +namespace Microsoft.AspNet.Builder { /// /// Configuration options for . diff --git a/src/Microsoft.AspNet.Authentication.JwtBearer/Events/AuthenticationFailedContext.cs b/src/Microsoft.AspNet.Authentication.JwtBearer/Events/AuthenticationFailedContext.cs index f8848d210d..02898af9c9 100644 --- a/src/Microsoft.AspNet.Authentication.JwtBearer/Events/AuthenticationFailedContext.cs +++ b/src/Microsoft.AspNet.Authentication.JwtBearer/Events/AuthenticationFailedContext.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; namespace Microsoft.AspNet.Authentication.JwtBearer diff --git a/src/Microsoft.AspNet.Authentication.JwtBearer/Events/BaseJwtBearerContext.cs b/src/Microsoft.AspNet.Authentication.JwtBearer/Events/BaseJwtBearerContext.cs index 91dd8cea22..50ed9ffc5f 100644 --- a/src/Microsoft.AspNet.Authentication.JwtBearer/Events/BaseJwtBearerContext.cs +++ b/src/Microsoft.AspNet.Authentication.JwtBearer/Events/BaseJwtBearerContext.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; namespace Microsoft.AspNet.Authentication.JwtBearer diff --git a/src/Microsoft.AspNet.Authentication.JwtBearer/Events/JwtBearerChallengeContext.cs b/src/Microsoft.AspNet.Authentication.JwtBearer/Events/JwtBearerChallengeContext.cs index ae6b9d4c69..403e8ab7fd 100644 --- a/src/Microsoft.AspNet.Authentication.JwtBearer/Events/JwtBearerChallengeContext.cs +++ b/src/Microsoft.AspNet.Authentication.JwtBearer/Events/JwtBearerChallengeContext.cs @@ -1,6 +1,7 @@ // 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; diff --git a/src/Microsoft.AspNet.Authentication.JwtBearer/Events/ReceivedTokenContext.cs b/src/Microsoft.AspNet.Authentication.JwtBearer/Events/ReceivedTokenContext.cs index 0aadaf2a99..a0c7a98c29 100644 --- a/src/Microsoft.AspNet.Authentication.JwtBearer/Events/ReceivedTokenContext.cs +++ b/src/Microsoft.AspNet.Authentication.JwtBearer/Events/ReceivedTokenContext.cs @@ -1,6 +1,7 @@ // 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; namespace Microsoft.AspNet.Authentication.JwtBearer diff --git a/src/Microsoft.AspNet.Authentication.JwtBearer/Events/ReceivingTokenContext.cs b/src/Microsoft.AspNet.Authentication.JwtBearer/Events/ReceivingTokenContext.cs index b0d824f3f7..16ee6c1cee 100644 --- a/src/Microsoft.AspNet.Authentication.JwtBearer/Events/ReceivingTokenContext.cs +++ b/src/Microsoft.AspNet.Authentication.JwtBearer/Events/ReceivingTokenContext.cs @@ -1,6 +1,7 @@ // 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; namespace Microsoft.AspNet.Authentication.JwtBearer diff --git a/src/Microsoft.AspNet.Authentication.JwtBearer/Events/TokenValidatedContext.cs b/src/Microsoft.AspNet.Authentication.JwtBearer/Events/TokenValidatedContext.cs index 9ae2fa68aa..1f6e24e922 100644 --- a/src/Microsoft.AspNet.Authentication.JwtBearer/Events/TokenValidatedContext.cs +++ b/src/Microsoft.AspNet.Authentication.JwtBearer/Events/TokenValidatedContext.cs @@ -1,6 +1,7 @@ // 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; namespace Microsoft.AspNet.Authentication.JwtBearer diff --git a/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerAppBuilderExtensions.cs b/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerAppBuilderExtensions.cs index da36d17f08..bea74d7412 100644 --- a/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerAppBuilderExtensions.cs +++ b/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerAppBuilderExtensions.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNet.Authentication.JwtBearer; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Builder { @@ -21,23 +22,15 @@ namespace Microsoft.AspNet.Builder /// See also http://tools.ietf.org/html/rfc6749 /// /// The to add the middleware to. - /// An action delegate to configure the provided . /// A reference to this instance after the operation has completed. - public static IApplicationBuilder UseJwtBearerAuthentication(this IApplicationBuilder app, Action configureOptions) + public static IApplicationBuilder UseJwtBearerAuthentication(this IApplicationBuilder app) { if (app == null) { throw new ArgumentNullException(nameof(app)); } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - var options = new JwtBearerOptions(); - configureOptions(options); - - return app.UseMiddleware(options); + return app.UseMiddleware(); } /// @@ -63,7 +56,7 @@ namespace Microsoft.AspNet.Builder throw new ArgumentNullException(nameof(options)); } - return app.UseMiddleware(options); + return app.UseMiddleware(Options.Create(options)); } } } diff --git a/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerHandler.cs b/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerHandler.cs index 08640019c9..be6e83c036 100644 --- a/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerHandler.cs +++ b/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerHandler.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Features.Authentication; diff --git a/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerMiddleware.cs b/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerMiddleware.cs index ad518b9667..7102cb61af 100644 --- a/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerMiddleware.cs +++ b/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerMiddleware.cs @@ -4,8 +4,10 @@ using System; using System.Net.Http; using System.Text.Encodings.Web; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols.OpenIdConnect; @@ -27,7 +29,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer RequestDelegate next, ILoggerFactory loggerFactory, UrlEncoder encoder, - JwtBearerOptions options) + IOptions options) : base(next, options, loggerFactory, encoder) { if (next == null) diff --git a/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerOptions.cs b/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerOptions.cs index ad2160c06a..b028d0b5e8 100644 --- a/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerOptions.cs +++ b/src/Microsoft.AspNet.Authentication.JwtBearer/JwtBearerOptions.cs @@ -6,11 +6,13 @@ using System.Collections.Generic; using System.ComponentModel; using System.IdentityModel.Tokens.Jwt; using System.Net.Http; +using Microsoft.AspNet.Authentication; +using Microsoft.AspNet.Authentication.JwtBearer; using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Tokens; -namespace Microsoft.AspNet.Authentication.JwtBearer +namespace Microsoft.AspNet.Builder { /// /// Options class provides information needed to control Bearer Authentication middleware behavior diff --git a/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountAppBuilderExtensions.cs b/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountAppBuilderExtensions.cs index 4066fa4ed7..1986227da3 100644 --- a/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountAppBuilderExtensions.cs +++ b/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountAppBuilderExtensions.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNet.Authentication.MicrosoftAccount; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Builder { @@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder /// Adds the middleware to the specified , which enables Microsoft Account authentication capabilities. /// /// The to add the middleware to. - /// An action delegate to configure the provided . /// A reference to this instance after the operation has completed. - public static IApplicationBuilder UseMicrosoftAccountAuthentication(this IApplicationBuilder app, Action configureOptions) + public static IApplicationBuilder UseMicrosoftAccountAuthentication(this IApplicationBuilder app) { if (app == null) { throw new ArgumentNullException(nameof(app)); } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - var options = new MicrosoftAccountOptions(); - configureOptions(options); - - return app.UseMiddleware(options); + return app.UseMiddleware(); } /// @@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder throw new ArgumentNullException(nameof(options)); } - return app.UseMiddleware(options); + return app.UseMiddleware(Options.Create(options)); } } } diff --git a/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountHandler.cs b/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountHandler.cs index 35dcc92239..f28c7ffc7f 100644 --- a/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountHandler.cs +++ b/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountHandler.cs @@ -6,6 +6,7 @@ using System.Net.Http.Headers; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Authentication.OAuth; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http.Authentication; using Newtonsoft.Json.Linq; diff --git a/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountMiddleware.cs b/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountMiddleware.cs index c398b9279e..5f0e36bb45 100644 --- a/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountMiddleware.cs +++ b/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountMiddleware.cs @@ -4,6 +4,7 @@ using System; using System.Text.Encodings.Web; using Microsoft.AspNet.Authentication.OAuth; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.Http; using Microsoft.Extensions.Logging; @@ -32,7 +33,7 @@ namespace Microsoft.AspNet.Authentication.MicrosoftAccount ILoggerFactory loggerFactory, UrlEncoder encoder, IOptions sharedOptions, - MicrosoftAccountOptions options) + IOptions options) : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options) { if (next == null) diff --git a/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountOptions.cs b/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountOptions.cs index 3339cf4ccd..392df69bf7 100644 --- a/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountOptions.cs +++ b/src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountOptions.cs @@ -2,9 +2,9 @@ // 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.Authentication.OAuth; +using Microsoft.AspNet.Authentication.MicrosoftAccount; -namespace Microsoft.AspNet.Authentication.MicrosoftAccount +namespace Microsoft.AspNet.Builder { /// /// Configuration options for . diff --git a/src/Microsoft.AspNet.Authentication.OAuth/Events/OAuthCreatingTicketContext.cs b/src/Microsoft.AspNet.Authentication.OAuth/Events/OAuthCreatingTicketContext.cs index 835bb2e3ae..c2b35349ee 100644 --- a/src/Microsoft.AspNet.Authentication.OAuth/Events/OAuthCreatingTicketContext.cs +++ b/src/Microsoft.AspNet.Authentication.OAuth/Events/OAuthCreatingTicketContext.cs @@ -5,8 +5,8 @@ using System; using System.Globalization; using System.Net.Http; using System.Security.Claims; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; -using Microsoft.AspNet.Http.Authentication; using Newtonsoft.Json.Linq; namespace Microsoft.AspNet.Authentication.OAuth diff --git a/src/Microsoft.AspNet.Authentication.OAuth/Events/OAuthRedirectToAuthorizationContext.cs b/src/Microsoft.AspNet.Authentication.OAuth/Events/OAuthRedirectToAuthorizationContext.cs index 7cc85f11a1..8e3599605f 100644 --- a/src/Microsoft.AspNet.Authentication.OAuth/Events/OAuthRedirectToAuthorizationContext.cs +++ b/src/Microsoft.AspNet.Authentication.OAuth/Events/OAuthRedirectToAuthorizationContext.cs @@ -1,6 +1,7 @@ // 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; diff --git a/src/Microsoft.AspNet.Authentication.OAuth/OAuthAppBuilderExtensions.cs b/src/Microsoft.AspNet.Authentication.OAuth/OAuthAppBuilderExtensions.cs index 5599407ca3..8d71400bae 100644 --- a/src/Microsoft.AspNet.Authentication.OAuth/OAuthAppBuilderExtensions.cs +++ b/src/Microsoft.AspNet.Authentication.OAuth/OAuthAppBuilderExtensions.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNet.Authentication.OAuth; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Builder { @@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder /// Adds the middleware to the specified , which enables OAuth 2.0 authentication capabilities. /// /// The to add the middleware to. - /// An action delegate to configure the provided . /// A reference to this instance after the operation has completed. - public static IApplicationBuilder UseOAuthAuthentication(this IApplicationBuilder app, Action configureOptions) + public static IApplicationBuilder UseOAuthAuthentication(this IApplicationBuilder app) { if (app == null) { throw new ArgumentNullException(nameof(app)); } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - var options = new OAuthOptions(); - configureOptions(options); - - return app.UseMiddleware>(options); + return app.UseMiddleware>(); } /// @@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder throw new ArgumentNullException(nameof(options)); } - return app.UseMiddleware>(options); + return app.UseMiddleware>(Options.Create(options)); } } } diff --git a/src/Microsoft.AspNet.Authentication.OAuth/OAuthHandler.cs b/src/Microsoft.AspNet.Authentication.OAuth/OAuthHandler.cs index 6f197d86bc..632932a3fb 100644 --- a/src/Microsoft.AspNet.Authentication.OAuth/OAuthHandler.cs +++ b/src/Microsoft.AspNet.Authentication.OAuth/OAuthHandler.cs @@ -9,6 +9,7 @@ using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Extensions; diff --git a/src/Microsoft.AspNet.Authentication.OAuth/OAuthMiddleware.cs b/src/Microsoft.AspNet.Authentication.OAuth/OAuthMiddleware.cs index ea145fa6de..72d34cbf78 100644 --- a/src/Microsoft.AspNet.Authentication.OAuth/OAuthMiddleware.cs +++ b/src/Microsoft.AspNet.Authentication.OAuth/OAuthMiddleware.cs @@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Net.Http; using System.Text.Encodings.Web; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.Http; using Microsoft.Extensions.Logging; @@ -32,7 +33,7 @@ namespace Microsoft.AspNet.Authentication.OAuth ILoggerFactory loggerFactory, UrlEncoder encoder, IOptions sharedOptions, - TOptions options) + IOptions options) : base(next, options, loggerFactory, encoder) { if (next == null) diff --git a/src/Microsoft.AspNet.Authentication.OAuth/OAuthOptions.cs b/src/Microsoft.AspNet.Authentication.OAuth/OAuthOptions.cs index a79c546725..d53e0a8bcd 100644 --- a/src/Microsoft.AspNet.Authentication.OAuth/OAuthOptions.cs +++ b/src/Microsoft.AspNet.Authentication.OAuth/OAuthOptions.cs @@ -2,9 +2,11 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; +using Microsoft.AspNet.Authentication; +using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Http.Authentication; -namespace Microsoft.AspNet.Authentication.OAuth +namespace Microsoft.AspNet.Builder { /// /// Configuration options for . diff --git a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthenticationFailedContext.cs b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthenticationFailedContext.cs index 6c8edb9f41..a120c24026 100644 --- a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthenticationFailedContext.cs +++ b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthenticationFailedContext.cs @@ -2,8 +2,8 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; -using Microsoft.IdentityModel.Protocols.OpenIdConnect; namespace Microsoft.AspNet.Authentication.OpenIdConnect { diff --git a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthenticationValidatedContext.cs b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthenticationValidatedContext.cs index f9998b83e7..2469ef5c86 100644 --- a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthenticationValidatedContext.cs +++ b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthenticationValidatedContext.cs @@ -1,6 +1,7 @@ // 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.IdentityModel.Protocols.OpenIdConnect; diff --git a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthorizationCodeReceivedContext.cs b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthorizationCodeReceivedContext.cs index 59f4d49115..f43be81981 100644 --- a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthorizationCodeReceivedContext.cs +++ b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthorizationCodeReceivedContext.cs @@ -3,6 +3,7 @@ using System.Diagnostics.CodeAnalysis; using System.IdentityModel.Tokens.Jwt; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; diff --git a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthorizationResponseReceivedContext.cs b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthorizationResponseReceivedContext.cs index 8e8b86a13a..e0c74c8db5 100644 --- a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthorizationResponseReceivedContext.cs +++ b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/AuthorizationResponseReceivedContext.cs @@ -1,9 +1,9 @@ // 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.IdentityModel.Protocols.OpenIdConnect; namespace Microsoft.AspNet.Authentication.OpenIdConnect { diff --git a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/BaseOpenIdConnectContext.cs b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/BaseOpenIdConnectContext.cs index 76d63e27b1..e207c836a5 100644 --- a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/BaseOpenIdConnectContext.cs +++ b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/BaseOpenIdConnectContext.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.IdentityModel.Protocols.OpenIdConnect; diff --git a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/MessageReceivedContext.cs b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/MessageReceivedContext.cs index 6439257cba..cb42c0f9bc 100644 --- a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/MessageReceivedContext.cs +++ b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/MessageReceivedContext.cs @@ -1,8 +1,8 @@ // 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.IdentityModel.Protocols.OpenIdConnect; namespace Microsoft.AspNet.Authentication.OpenIdConnect { diff --git a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/RedirectContext.cs b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/RedirectContext.cs index fa1ef30d08..a87c3398ed 100644 --- a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/RedirectContext.cs +++ b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/RedirectContext.cs @@ -1,9 +1,9 @@ // 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.IdentityModel.Protocols.OpenIdConnect; namespace Microsoft.AspNet.Authentication.OpenIdConnect { diff --git a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/TokenResponseReceivedContext.cs b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/TokenResponseReceivedContext.cs index e9522f70d8..0e12bc2914 100644 --- a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/TokenResponseReceivedContext.cs +++ b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/TokenResponseReceivedContext.cs @@ -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.IdentityModel.Protocols.OpenIdConnect; diff --git a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/UserInformationReceivedContext.cs b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/UserInformationReceivedContext.cs index fa0bc92773..80935354af 100644 --- a/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/UserInformationReceivedContext.cs +++ b/src/Microsoft.AspNet.Authentication.OpenIdConnect/Events/UserInformationReceivedContext.cs @@ -1,8 +1,8 @@ // 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.IdentityModel.Protocols.OpenIdConnect; using Newtonsoft.Json.Linq; namespace Microsoft.AspNet.Authentication.OpenIdConnect diff --git a/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectAppBuilderExtensions.cs b/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectAppBuilderExtensions.cs index 329820417c..63cfe5009a 100644 --- a/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectAppBuilderExtensions.cs +++ b/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectAppBuilderExtensions.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNet.Authentication.OpenIdConnect; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Builder { @@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder /// Adds the middleware to the specified , which enables OpenID Connect authentication capabilities. /// /// The to add the middleware to. - /// An action delegate to configure the provided . /// A reference to this instance after the operation has completed. - public static IApplicationBuilder UseOpenIdConnectAuthentication(this IApplicationBuilder app, Action configureOptions) + public static IApplicationBuilder UseOpenIdConnectAuthentication(this IApplicationBuilder app) { if (app == null) { throw new ArgumentNullException(nameof(app)); } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - var options = new OpenIdConnectOptions(); - configureOptions(options); - - return app.UseMiddleware(options); + return app.UseMiddleware(); } /// @@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder throw new ArgumentNullException(nameof(options)); } - return app.UseMiddleware(options); + return app.UseMiddleware(Options.Create(options)); } } } diff --git a/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectHandler.cs b/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectHandler.cs index 2d157e48c3..12d61e334b 100644 --- a/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectHandler.cs +++ b/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectHandler.cs @@ -13,6 +13,7 @@ using System.Security.Cryptography; using System.Text; using System.Text.Encodings.Web; using System.Threading.Tasks; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Features.Authentication; diff --git a/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectMiddleware.cs b/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectMiddleware.cs index a6f9971705..5dcd74d3c1 100644 --- a/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectMiddleware.cs +++ b/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectMiddleware.cs @@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Net.Http; using System.Text; using System.Text.Encodings.Web; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.Http; using Microsoft.Extensions.Logging; @@ -38,7 +39,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect UrlEncoder encoder, IServiceProvider services, IOptions sharedOptions, - OpenIdConnectOptions options, + IOptions options, HtmlEncoder htmlEncoder) : base(next, options, loggerFactory, encoder) { diff --git a/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectOptions.cs b/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectOptions.cs index 06b7442de0..af7a621de0 100644 --- a/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectOptions.cs +++ b/src/Microsoft.AspNet.Authentication.OpenIdConnect/OpenIdConnectOptions.cs @@ -5,13 +5,15 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IdentityModel.Tokens.Jwt; +using Microsoft.AspNet.Authentication; +using Microsoft.AspNet.Authentication.OpenIdConnect; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Tokens; -namespace Microsoft.AspNet.Authentication.OpenIdConnect +namespace Microsoft.AspNet.Builder { /// /// Configuration options for diff --git a/src/Microsoft.AspNet.Authentication.Twitter/Events/BaseTwitterContext.cs b/src/Microsoft.AspNet.Authentication.Twitter/Events/BaseTwitterContext.cs index 5a2f337581..d928fdcc71 100644 --- a/src/Microsoft.AspNet.Authentication.Twitter/Events/BaseTwitterContext.cs +++ b/src/Microsoft.AspNet.Authentication.Twitter/Events/BaseTwitterContext.cs @@ -1,6 +1,7 @@ // 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; namespace Microsoft.AspNet.Authentication.Twitter diff --git a/src/Microsoft.AspNet.Authentication.Twitter/Events/TwitterCreatingTicketContext.cs b/src/Microsoft.AspNet.Authentication.Twitter/Events/TwitterCreatingTicketContext.cs index d727eeb152..d5537ef95c 100644 --- a/src/Microsoft.AspNet.Authentication.Twitter/Events/TwitterCreatingTicketContext.cs +++ b/src/Microsoft.AspNet.Authentication.Twitter/Events/TwitterCreatingTicketContext.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Security.Claims; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; diff --git a/src/Microsoft.AspNet.Authentication.Twitter/Events/TwitterRedirectToAuthorizationEndpointContext.cs b/src/Microsoft.AspNet.Authentication.Twitter/Events/TwitterRedirectToAuthorizationEndpointContext.cs index 455f522029..5569e82735 100644 --- a/src/Microsoft.AspNet.Authentication.Twitter/Events/TwitterRedirectToAuthorizationEndpointContext.cs +++ b/src/Microsoft.AspNet.Authentication.Twitter/Events/TwitterRedirectToAuthorizationEndpointContext.cs @@ -1,6 +1,7 @@ // 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; diff --git a/src/Microsoft.AspNet.Authentication.Twitter/TwitterAppBuilderExtensions.cs b/src/Microsoft.AspNet.Authentication.Twitter/TwitterAppBuilderExtensions.cs index 1701122b0a..6303707521 100644 --- a/src/Microsoft.AspNet.Authentication.Twitter/TwitterAppBuilderExtensions.cs +++ b/src/Microsoft.AspNet.Authentication.Twitter/TwitterAppBuilderExtensions.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNet.Authentication.Twitter; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Builder { @@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder /// Adds the middleware to the specified , which enables Twitter authentication capabilities. /// /// The to add the middleware to. - /// An action delegate to configure the provided . /// A reference to this instance after the operation has completed. - public static IApplicationBuilder UseTwitterAuthentication(this IApplicationBuilder app, Action configureOptions) + public static IApplicationBuilder UseTwitterAuthentication(this IApplicationBuilder app) { if (app == null) { throw new ArgumentNullException(nameof(app)); } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - var options = new TwitterOptions(); - configureOptions(options); - - return app.UseMiddleware(options); + return app.UseMiddleware(); } /// @@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder throw new ArgumentNullException(nameof(options)); } - return app.UseMiddleware(options); + return app.UseMiddleware(Options.Create(options)); } } } diff --git a/src/Microsoft.AspNet.Authentication.Twitter/TwitterHandler.cs b/src/Microsoft.AspNet.Authentication.Twitter/TwitterHandler.cs index 0552ed2d76..3de3b37fdf 100644 --- a/src/Microsoft.AspNet.Authentication.Twitter/TwitterHandler.cs +++ b/src/Microsoft.AspNet.Authentication.Twitter/TwitterHandler.cs @@ -9,6 +9,7 @@ using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Features.Authentication; diff --git a/src/Microsoft.AspNet.Authentication.Twitter/TwitterMiddleware.cs b/src/Microsoft.AspNet.Authentication.Twitter/TwitterMiddleware.cs index e1a1c17211..6b708a3a73 100644 --- a/src/Microsoft.AspNet.Authentication.Twitter/TwitterMiddleware.cs +++ b/src/Microsoft.AspNet.Authentication.Twitter/TwitterMiddleware.cs @@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Net.Http; using System.Text.Encodings.Web; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.Http; using Microsoft.Extensions.Logging; @@ -37,7 +38,7 @@ namespace Microsoft.AspNet.Authentication.Twitter ILoggerFactory loggerFactory, UrlEncoder encoder, IOptions sharedOptions, - TwitterOptions options) + IOptions options) : base(next, options, loggerFactory, encoder) { if (next == null) diff --git a/src/Microsoft.AspNet.Authentication.Twitter/TwitterOptions.cs b/src/Microsoft.AspNet.Authentication.Twitter/TwitterOptions.cs index 85e266326a..19a3ca78aa 100644 --- a/src/Microsoft.AspNet.Authentication.Twitter/TwitterOptions.cs +++ b/src/Microsoft.AspNet.Authentication.Twitter/TwitterOptions.cs @@ -2,10 +2,11 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Net.Http; +using Microsoft.AspNet.Authentication; +using Microsoft.AspNet.Authentication.Twitter; using Microsoft.AspNet.Http; -namespace Microsoft.AspNet.Authentication.Twitter +namespace Microsoft.AspNet.Builder { /// /// Options for the Twitter authentication middleware. diff --git a/src/Microsoft.AspNet.Authentication/AuthenticationHandler.cs b/src/Microsoft.AspNet.Authentication/AuthenticationHandler.cs index c45fdfa7e6..f68bddaf89 100644 --- a/src/Microsoft.AspNet.Authentication/AuthenticationHandler.cs +++ b/src/Microsoft.AspNet.Authentication/AuthenticationHandler.cs @@ -4,6 +4,7 @@ using System; using System.Text.Encodings.Web; using System.Threading.Tasks; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Features.Authentication; diff --git a/src/Microsoft.AspNet.Authentication/AuthenticationMiddleware.cs b/src/Microsoft.AspNet.Authentication/AuthenticationMiddleware.cs index ef7cb5056d..08e325bc0b 100644 --- a/src/Microsoft.AspNet.Authentication/AuthenticationMiddleware.cs +++ b/src/Microsoft.AspNet.Authentication/AuthenticationMiddleware.cs @@ -4,8 +4,10 @@ using System; using System.Text.Encodings.Web; using System.Threading.Tasks; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Authentication { @@ -15,7 +17,7 @@ namespace Microsoft.AspNet.Authentication protected AuthenticationMiddleware( RequestDelegate next, - TOptions options, + IOptions options, ILoggerFactory loggerFactory, UrlEncoder encoder) { @@ -39,7 +41,7 @@ namespace Microsoft.AspNet.Authentication throw new ArgumentNullException(nameof(encoder)); } - Options = options; + Options = options.Value; Logger = loggerFactory.CreateLogger(this.GetType().FullName); UrlEncoder = encoder; diff --git a/src/Microsoft.AspNet.Authentication/AuthenticationOptions.cs b/src/Microsoft.AspNet.Authentication/AuthenticationOptions.cs index 7583642443..5f8e562935 100644 --- a/src/Microsoft.AspNet.Authentication/AuthenticationOptions.cs +++ b/src/Microsoft.AspNet.Authentication/AuthenticationOptions.cs @@ -3,7 +3,7 @@ using Microsoft.AspNet.Http.Authentication; -namespace Microsoft.AspNet.Authentication +namespace Microsoft.AspNet.Builder { /// /// Base Options for all authentication middleware diff --git a/src/Microsoft.AspNet.Authentication/ClaimsTransformationAppBuilderExtensions.cs b/src/Microsoft.AspNet.Authentication/ClaimsTransformationAppBuilderExtensions.cs index 21f80419f7..7dfa482174 100644 --- a/src/Microsoft.AspNet.Authentication/ClaimsTransformationAppBuilderExtensions.cs +++ b/src/Microsoft.AspNet.Authentication/ClaimsTransformationAppBuilderExtensions.cs @@ -5,6 +5,7 @@ using System; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Authentication; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Builder { @@ -13,6 +14,21 @@ namespace Microsoft.AspNet.Builder /// public static class ClaimsTransformationAppBuilderExtensions { + /// + /// Adds the middleware to the specified , which enables claims transformation capabilities. + /// + /// The to add the middleware to. + /// A reference to this instance after the operation has completed. + public static IApplicationBuilder UseClaimsTransformation(this IApplicationBuilder app) + { + if (app == null) + { + throw new ArgumentNullException(nameof(app)); + } + + return app.UseMiddleware(); + } + /// /// Adds the middleware to the specified , which enables claims transformation capabilities. /// @@ -30,35 +46,12 @@ namespace Microsoft.AspNet.Builder 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 } }); } - - /// - /// Adds the middleware to the specified , which enables claims transformation capabilities. - /// - /// The to add the middleware to. - /// An action delegate to configure the provided . - /// A reference to this instance after the operation has completed. - public static IApplicationBuilder UseClaimsTransformation(this IApplicationBuilder app, Action 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(options); - } - + /// /// Adds the middleware to the specified , which enables claims transformation capabilities. /// @@ -76,7 +69,7 @@ namespace Microsoft.AspNet.Builder throw new ArgumentNullException(nameof(options)); } - return app.UseMiddleware(options); + return app.UseMiddleware(Options.Create(options)); } } } diff --git a/src/Microsoft.AspNet.Authentication/ClaimsTransformationMiddleware.cs b/src/Microsoft.AspNet.Authentication/ClaimsTransformationMiddleware.cs index c84777cd81..f490af4a4f 100644 --- a/src/Microsoft.AspNet.Authentication/ClaimsTransformationMiddleware.cs +++ b/src/Microsoft.AspNet.Authentication/ClaimsTransformationMiddleware.cs @@ -3,7 +3,9 @@ using System; using System.Threading.Tasks; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Authentication { @@ -13,7 +15,7 @@ namespace Microsoft.AspNet.Authentication public ClaimsTransformationMiddleware( RequestDelegate next, - ClaimsTransformationOptions options) + IOptions options) { if (next == null) { @@ -25,7 +27,7 @@ namespace Microsoft.AspNet.Authentication throw new ArgumentNullException(nameof(options)); } - Options = options; + Options = options.Value; _next = next; } diff --git a/src/Microsoft.AspNet.Authentication/ClaimsTransformationOptions.cs b/src/Microsoft.AspNet.Authentication/ClaimsTransformationOptions.cs index 19475ba023..e1ca6b9004 100644 --- a/src/Microsoft.AspNet.Authentication/ClaimsTransformationOptions.cs +++ b/src/Microsoft.AspNet.Authentication/ClaimsTransformationOptions.cs @@ -1,7 +1,9 @@ // 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. -namespace Microsoft.AspNet.Authentication +using Microsoft.AspNet.Authentication; + +namespace Microsoft.AspNet.Builder { public class ClaimsTransformationOptions { diff --git a/src/Microsoft.AspNet.Authentication/Events/TicketReceivedContext.cs b/src/Microsoft.AspNet.Authentication/Events/TicketReceivedContext.cs index 28f6649fee..0663248cf1 100644 --- a/src/Microsoft.AspNet.Authentication/Events/TicketReceivedContext.cs +++ b/src/Microsoft.AspNet.Authentication/Events/TicketReceivedContext.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Security.Claims; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; diff --git a/src/Microsoft.AspNet.Authentication/RemoteAuthenticationHandler.cs b/src/Microsoft.AspNet.Authentication/RemoteAuthenticationHandler.cs index dda9063697..cc1487d55d 100644 --- a/src/Microsoft.AspNet.Authentication/RemoteAuthenticationHandler.cs +++ b/src/Microsoft.AspNet.Authentication/RemoteAuthenticationHandler.cs @@ -3,6 +3,7 @@ using System; using System.Threading.Tasks; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http.Features.Authentication; using Microsoft.Extensions.Logging; diff --git a/src/Microsoft.AspNet.Authentication/RemoteAuthenticationOptions.cs b/src/Microsoft.AspNet.Authentication/RemoteAuthenticationOptions.cs index 5fb3b4caf6..afaee6c7b1 100644 --- a/src/Microsoft.AspNet.Authentication/RemoteAuthenticationOptions.cs +++ b/src/Microsoft.AspNet.Authentication/RemoteAuthenticationOptions.cs @@ -3,10 +3,10 @@ using System; using System.Net.Http; -using System.Threading.Tasks; using Microsoft.AspNet.Http; +using Microsoft.AspNet.Authentication; -namespace Microsoft.AspNet.Authentication +namespace Microsoft.AspNet.Builder { public class RemoteAuthenticationOptions : AuthenticationOptions { diff --git a/src/Microsoft.AspNet.Authorization/AuthorizationServiceCollectionExtensions.cs b/src/Microsoft.AspNet.Authorization/AuthorizationServiceCollectionExtensions.cs index dff8bf6fcd..599a8fb27c 100644 --- a/src/Microsoft.AspNet.Authorization/AuthorizationServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNet.Authorization/AuthorizationServiceCollectionExtensions.cs @@ -24,8 +24,7 @@ namespace Microsoft.Extensions.DependencyInjection { throw new ArgumentNullException(nameof(services)); } - - services.AddOptions(); + services.TryAdd(ServiceDescriptor.Transient()); services.TryAddEnumerable(ServiceDescriptor.Transient()); return services; diff --git a/src/Microsoft.AspNet.CookiePolicy/CookiePolicyAppBuilderExtensions.cs b/src/Microsoft.AspNet.CookiePolicy/CookiePolicyAppBuilderExtensions.cs index 95d52e55f0..02cbd22f96 100644 --- a/src/Microsoft.AspNet.CookiePolicy/CookiePolicyAppBuilderExtensions.cs +++ b/src/Microsoft.AspNet.CookiePolicy/CookiePolicyAppBuilderExtensions.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNet.CookiePolicy; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Builder { @@ -15,23 +16,15 @@ namespace Microsoft.AspNet.Builder /// Adds the middleware to the specified , which enables cookie policy capabilities. /// /// The to add the middleware to. - /// An action delegate to configure the provided . /// A reference to this instance after the operation has completed. - public static IApplicationBuilder UseCookiePolicy(this IApplicationBuilder app, Action configureOptions) + public static IApplicationBuilder UseCookiePolicy(this IApplicationBuilder app) { if (app == null) { throw new ArgumentNullException(nameof(app)); } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - var options = new CookiePolicyOptions(); - configureOptions(options); - - return app.UseMiddleware(options); + return app.UseMiddleware(); } /// @@ -51,7 +44,7 @@ namespace Microsoft.AspNet.Builder throw new ArgumentNullException(nameof(options)); } - return app.UseMiddleware(options); + return app.UseMiddleware(Options.Create(options)); } } } \ No newline at end of file diff --git a/src/Microsoft.AspNet.CookiePolicy/CookiePolicyMiddleware.cs b/src/Microsoft.AspNet.CookiePolicy/CookiePolicyMiddleware.cs index 5c49b9e180..2fb299d165 100644 --- a/src/Microsoft.AspNet.CookiePolicy/CookiePolicyMiddleware.cs +++ b/src/Microsoft.AspNet.CookiePolicy/CookiePolicyMiddleware.cs @@ -3,9 +3,10 @@ using System; using System.Threading.Tasks; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; -using Microsoft.AspNet.Http.Features; using Microsoft.AspNet.Http.Features.Internal; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.CookiePolicy { @@ -15,9 +16,9 @@ namespace Microsoft.AspNet.CookiePolicy public CookiePolicyMiddleware( RequestDelegate next, - CookiePolicyOptions options) + IOptions options) { - Options = options; + Options = options.Value; _next = next; } diff --git a/src/Microsoft.AspNet.CookiePolicy/CookiePolicyOptions.cs b/src/Microsoft.AspNet.CookiePolicy/CookiePolicyOptions.cs index ce5a866980..ffc2fa7b74 100644 --- a/src/Microsoft.AspNet.CookiePolicy/CookiePolicyOptions.cs +++ b/src/Microsoft.AspNet.CookiePolicy/CookiePolicyOptions.cs @@ -2,8 +2,9 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using Microsoft.AspNet.CookiePolicy; -namespace Microsoft.AspNet.CookiePolicy +namespace Microsoft.AspNet.Builder { public class CookiePolicyOptions { diff --git a/src/Microsoft.AspNet.CookiePolicy/project.json b/src/Microsoft.AspNet.CookiePolicy/project.json index 3eab1d58f9..79ccda4a15 100644 --- a/src/Microsoft.AspNet.CookiePolicy/project.json +++ b/src/Microsoft.AspNet.CookiePolicy/project.json @@ -10,7 +10,8 @@ "keyFile": "../../tools/Key.snk" }, "dependencies": { - "Microsoft.AspNet.Http": "1.0.0-*" + "Microsoft.AspNet.Http": "1.0.0-*", + "Microsoft.Extensions.Options": "1.0.0-*" }, "frameworks": { "net451": {}, diff --git a/test/Microsoft.AspNet.Authentication.Test/AuthenticationHandlerFacts.cs b/test/Microsoft.AspNet.Authentication.Test/AuthenticationHandlerFacts.cs index 073d6f1e4b..b5935938ae 100644 --- a/test/Microsoft.AspNet.Authentication.Test/AuthenticationHandlerFacts.cs +++ b/test/Microsoft.AspNet.Authentication.Test/AuthenticationHandlerFacts.cs @@ -6,6 +6,7 @@ using System.IO; using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Features; diff --git a/test/Microsoft.AspNet.Authentication.Test/Cookies/CookieMiddlewareTests.cs b/test/Microsoft.AspNet.Authentication.Test/Cookies/CookieMiddlewareTests.cs index ffcf6d8792..7827566a9f 100644 --- a/test/Microsoft.AspNet.Authentication.Test/Cookies/CookieMiddlewareTests.cs +++ b/test/Microsoft.AspNet.Authentication.Test/Cookies/CookieMiddlewareTests.cs @@ -27,9 +27,7 @@ namespace Microsoft.AspNet.Authentication.Cookies [Fact] public async Task NormalRequestPassesThrough() { - var server = CreateServer(options => - { - }); + var server = CreateServer(new CookieAuthenticationOptions()); var response = await server.CreateClient().GetAsync("http://example.com/normal"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } @@ -37,10 +35,10 @@ namespace Microsoft.AspNet.Authentication.Cookies [Fact] public async Task AjaxLoginRedirectToReturnUrlTurnsInto200WithLocationHeader() { - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.AutomaticChallenge = true; - options.LoginPath = "/login"; + AutomaticChallenge = true, + LoginPath = "/login" }); var transaction = await SendAsync(server, "http://example.com/protected?X-Requested-With=XMLHttpRequest"); @@ -53,9 +51,9 @@ namespace Microsoft.AspNet.Authentication.Cookies [Fact] 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"); @@ -68,9 +66,9 @@ namespace Microsoft.AspNet.Authentication.Cookies [Fact] 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=/"); @@ -83,9 +81,7 @@ namespace Microsoft.AspNet.Authentication.Cookies [Fact] 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=/"); Assert.Equal(HttpStatusCode.Unauthorized, transaction.Response.StatusCode); @@ -100,10 +96,10 @@ namespace Microsoft.AspNet.Authentication.Cookies [InlineData(false)] public async Task ProtectedRequestShouldRedirectToLoginOnlyWhenAutomatic(bool auto) { - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.LoginPath = new PathString("/login"); - options.AutomaticChallenge = auto; + LoginPath = new PathString("/login"), + AutomaticChallenge = auto }); var transaction = await SendAsync(server, "http://example.com/protected"); @@ -120,7 +116,10 @@ namespace Microsoft.AspNet.Authentication.Cookies [Fact] 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"); @@ -151,10 +150,10 @@ namespace Microsoft.AspNet.Authentication.Cookies [Fact] public async Task SignInCausesDefaultCookieToBeCreated() { - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.LoginPath = new PathString("/login"); - options.CookieName = "TestCookie"; + LoginPath = new PathString("/login"), + CookieName = "TestCookie" }, SignInAsAlice); var transaction = await SendAsync(server, "http://example.com/testpath"); @@ -171,10 +170,10 @@ namespace Microsoft.AspNet.Authentication.Cookies [Fact] public async Task SignInWrongAuthTypeThrows() { - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.LoginPath = new PathString("/login"); - options.CookieName = "TestCookie"; + LoginPath = new PathString("/login"), + CookieName = "TestCookie" }, SignInAsWrong); await Assert.ThrowsAsync(async () => await SendAsync(server, "http://example.com/testpath")); @@ -183,10 +182,10 @@ namespace Microsoft.AspNet.Authentication.Cookies [Fact] public async Task SignOutWrongAuthTypeThrows() { - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.LoginPath = new PathString("/login"); - options.CookieName = "TestCookie"; + LoginPath = new PathString("/login"), + CookieName = "TestCookie" }, SignOutAsWrong); await Assert.ThrowsAsync(async () => await SendAsync(server, "http://example.com/testpath")); @@ -204,11 +203,11 @@ namespace Microsoft.AspNet.Authentication.Cookies string requestUri, bool shouldBeSecureOnly) { - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.LoginPath = new PathString("/login"); - options.CookieName = "TestCookie"; - options.CookieSecure = cookieSecureOption; + LoginPath = new PathString("/login"), + CookieName = "TestCookie", + CookieSecure = cookieSecureOption }, SignInAsAlice); var transaction = await SendAsync(server, requestUri); @@ -227,13 +226,13 @@ namespace Microsoft.AspNet.Authentication.Cookies [Fact] public async Task CookieOptionsAlterSetCookieHeader() { - TestServer server1 = CreateServer(options => + TestServer server1 = CreateServer(new CookieAuthenticationOptions { - options.CookieName = "TestCookie"; - options.CookiePath = "/foo"; - options.CookieDomain = "another.com"; - options.CookieSecure = CookieSecureOption.Always; - options.CookieHttpOnly = true; + CookieName = "TestCookie", + CookiePath = "/foo", + CookieDomain = "another.com", + CookieSecure = CookieSecureOption.Always, + CookieHttpOnly = true }, SignInAsAlice, new Uri("http://example.com/base")); 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(" httponly", setCookie1); - var server2 = CreateServer(options => + var server2 = CreateServer(new CookieAuthenticationOptions { - options.CookieName = "SecondCookie"; - options.CookieSecure = CookieSecureOption.Never; - options.CookieHttpOnly = false; + CookieName = "SecondCookie", + CookieSecure = CookieSecureOption.Never, + CookieHttpOnly = false }, SignInAsAlice, new Uri("http://example.com/base")); var transaction2 = await SendAsync(server2, "http://example.com/base/testpath"); @@ -268,9 +267,9 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieContainsIdentity() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; + SystemClock = clock }, SignInAsAlice); var transaction1 = await SendAsync(server, "http://example.com/testpath"); @@ -284,24 +283,27 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieAppliesClaimsTransform() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; + SystemClock = clock }, SignInAsAlice, 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 - var id = new ClaimsIdentity("xform"); - id.AddClaim(new Claim("xform", "yup")); - p.AddIdentity(id); + if (!p.Identities.Any(i => i.AuthenticationType == "xform")) + { + // REVIEW: Xform runs twice, once on Authenticate, and then once from the middleware + 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() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; - options.ExpireTimeSpan = TimeSpan.FromMinutes(10); - options.SlidingExpiration = false; + SystemClock = clock, + ExpireTimeSpan = TimeSpan.FromMinutes(10), + SlidingExpiration = false }, SignInAsAlice); var transaction1 = await SendAsync(server, "http://example.com/testpath"); @@ -349,11 +351,11 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieExpirationCanBeOverridenInSignin() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; - options.ExpireTimeSpan = TimeSpan.FromMinutes(10); - options.SlidingExpiration = false; + SystemClock = clock, + ExpireTimeSpan = TimeSpan.FromMinutes(10), + SlidingExpiration = false }, context => context.Authentication.SignInAsync("Cookies", @@ -384,18 +386,18 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task ExpiredCookieWithValidatorStillExpired() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; - options.ExpireTimeSpan = TimeSpan.FromMinutes(10); - options.Events = new CookieAuthenticationEvents + SystemClock = clock, + ExpireTimeSpan = TimeSpan.FromMinutes(10), + Events = new CookieAuthenticationEvents { OnValidatePrincipal = ctx => { ctx.ShouldRenew = true; return Task.FromResult(0); } - }; + } }, context => context.Authentication.SignInAsync("Cookies", @@ -414,12 +416,12 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieCanBeRejectedAndSignedOutByValidator() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; - options.ExpireTimeSpan = TimeSpan.FromMinutes(10); - options.SlidingExpiration = false; - options.Events = new CookieAuthenticationEvents + SystemClock = clock, + ExpireTimeSpan = TimeSpan.FromMinutes(10), + SlidingExpiration = false, + Events = new CookieAuthenticationEvents { OnValidatePrincipal = ctx => { @@ -427,7 +429,7 @@ namespace Microsoft.AspNet.Authentication.Cookies ctx.HttpContext.Authentication.SignOutAsync("Cookies"); return Task.FromResult(0); } - }; + } }, context => context.Authentication.SignInAsync("Cookies", @@ -444,19 +446,19 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieCanBeRenewedByValidator() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; - options.ExpireTimeSpan = TimeSpan.FromMinutes(10); - options.SlidingExpiration = false; - options.Events = new CookieAuthenticationEvents + SystemClock = clock, + ExpireTimeSpan = TimeSpan.FromMinutes(10), + SlidingExpiration = false, + Events = new CookieAuthenticationEvents { OnValidatePrincipal = ctx => { ctx.ShouldRenew = true; return Task.FromResult(0); } - }; + } }, context => context.Authentication.SignInAsync("Cookies", @@ -491,18 +493,18 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieCanBeRenewedByValidatorWithSlidingExpiry() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; - options.ExpireTimeSpan = TimeSpan.FromMinutes(10); - options.Events = new CookieAuthenticationEvents + SystemClock = clock, + ExpireTimeSpan = TimeSpan.FromMinutes(10), + Events = new CookieAuthenticationEvents { OnValidatePrincipal = ctx => { ctx.ShouldRenew = true; return Task.FromResult(0); } - }; + } }, context => context.Authentication.SignInAsync("Cookies", @@ -537,19 +539,19 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieValidatorOnlyCalledOnce() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; - options.ExpireTimeSpan = TimeSpan.FromMinutes(10); - options.SlidingExpiration = false; - options.Events = new CookieAuthenticationEvents + SystemClock = clock, + ExpireTimeSpan = TimeSpan.FromMinutes(10), + SlidingExpiration = false, + Events = new CookieAuthenticationEvents { OnValidatePrincipal = ctx => { ctx.ShouldRenew = true; return Task.FromResult(0); } - }; + } }, context => context.Authentication.SignInAsync("Cookies", @@ -588,12 +590,12 @@ namespace Microsoft.AspNet.Authentication.Cookies var clock = new TestClock(); DateTimeOffset? lastValidateIssuedDate = null; DateTimeOffset? lastExpiresDate = null; - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; - options.ExpireTimeSpan = TimeSpan.FromMinutes(10); - options.SlidingExpiration = sliding; - options.Events = new CookieAuthenticationEvents + SystemClock = clock, + ExpireTimeSpan = TimeSpan.FromMinutes(10), + SlidingExpiration = sliding, + Events = new CookieAuthenticationEvents { OnValidatePrincipal = ctx => { @@ -602,7 +604,7 @@ namespace Microsoft.AspNet.Authentication.Cookies ctx.ShouldRenew = true; return Task.FromResult(0); } - }; + } }, context => context.Authentication.SignInAsync("Cookies", @@ -640,19 +642,19 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieExpirationCanBeOverridenInEvent() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; - options.ExpireTimeSpan = TimeSpan.FromMinutes(10); - options.SlidingExpiration = false; - options.Events = new CookieAuthenticationEvents() + SystemClock = clock, + ExpireTimeSpan = TimeSpan.FromMinutes(10), + SlidingExpiration = false, + Events = new CookieAuthenticationEvents() { OnSigningIn = context => { context.Properties.ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5)); return Task.FromResult(0); } - }; + } }, SignInAsAlice); var transaction1 = await SendAsync(server, "http://example.com/testpath"); @@ -678,11 +680,11 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieIsRenewedWithSlidingExpiration() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; - options.ExpireTimeSpan = TimeSpan.FromMinutes(10); - options.SlidingExpiration = true; + SystemClock = clock, + ExpireTimeSpan = TimeSpan.FromMinutes(10), + SlidingExpiration = true }, SignInAsAlice); var transaction1 = await SendAsync(server, "http://example.com/testpath"); @@ -715,7 +717,7 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieUsesPathBaseByDefault() { var clock = new TestClock(); - var server = CreateServer(options => { }, + var server = CreateServer(new CookieAuthenticationOptions(), context => { Assert.Equal(new PathString("/base"), context.Request.PathBase); @@ -734,10 +736,10 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieTurnsChallengeIntoForbidWithCookie(bool automatic) { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.AutomaticAuthenticate = automatic; - options.SystemClock = clock; + AutomaticAuthenticate = automatic, + SystemClock = clock }, SignInAsAlice); @@ -758,10 +760,10 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieChallengeRedirectsToLoginWithoutCookie(bool automatic) { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.AutomaticAuthenticate = automatic; - options.SystemClock = clock; + AutomaticAuthenticate = automatic, + SystemClock = clock }, SignInAsAlice); @@ -779,10 +781,10 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieForbidRedirectsWithoutCookie(bool automatic) { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.AutomaticAuthenticate = automatic; - options.SystemClock = clock; + AutomaticAuthenticate = automatic, + SystemClock = clock }, SignInAsAlice); @@ -798,10 +800,10 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieTurns401ToAccessDeniedWhenSetWithCookie() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; - options.AccessDeniedPath = new PathString("/accessdenied"); + SystemClock = clock, + AccessDeniedPath = new PathString("/accessdenied") }, SignInAsAlice); @@ -819,10 +821,10 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieChallengeRedirectsWithLoginPath() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; - options.LoginPath = new PathString("/page"); + SystemClock = clock, + LoginPath = new PathString("/page") }); var transaction1 = await SendAsync(server, "http://example.com/testpath"); @@ -836,10 +838,10 @@ namespace Microsoft.AspNet.Authentication.Cookies public async Task CookieChallengeWithUnauthorizedRedirectsToLoginIfNotAuthenticated() { var clock = new TestClock(); - var server = CreateServer(options => + var server = CreateServer(new CookieAuthenticationOptions { - options.SystemClock = clock; - options.LoginPath = new PathString("/page"); + SystemClock = clock, + LoginPath = new PathString("/page") }); var transaction1 = await SendAsync(server, "http://example.com/testpath"); @@ -855,7 +857,10 @@ namespace Microsoft.AspNet.Authentication.Cookies var builder = new WebApplicationBuilder() .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 = "/" }))); }) .ConfigureServices(services => services.AddAuthentication()); @@ -895,7 +900,10 @@ namespace Microsoft.AspNet.Authentication.Cookies var builder = new WebApplicationBuilder() .Configure(app => { - app.UseCookieAuthentication(options => options.CookieName = "One"); + app.UseCookieAuthentication(new CookieAuthenticationOptions + { + CookieName = "One" + }); app.UseCookieAuthentication(); 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() .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", new ClaimsPrincipal()))); }) @@ -932,7 +943,10 @@ namespace Microsoft.AspNet.Authentication.Cookies var builder = new WebApplicationBuilder() .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", new ClaimsPrincipal()))); }) @@ -954,7 +968,10 @@ namespace Microsoft.AspNet.Authentication.Cookies var builder = new WebApplicationBuilder() .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"))); }) .ConfigureServices(services => services.AddAuthentication()); @@ -971,7 +988,10 @@ namespace Microsoft.AspNet.Authentication.Cookies var builder = new WebApplicationBuilder() .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"))); }) .ConfigureServices(services => services.AddAuthentication()); @@ -992,7 +1012,10 @@ namespace Microsoft.AspNet.Authentication.Cookies var builder = new WebApplicationBuilder() .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"))); }) .ConfigureServices(services => services.AddAuthentication()); @@ -1012,7 +1035,10 @@ namespace Microsoft.AspNet.Authentication.Cookies .Configure(app => 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 = "/" }))); })) .ConfigureServices(services => services.AddAuthentication()); @@ -1033,7 +1059,10 @@ namespace Microsoft.AspNet.Authentication.Cookies .Configure(app => 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"))); })) .ConfigureServices(services => services.AddAuthentication()); @@ -1054,10 +1083,10 @@ namespace Microsoft.AspNet.Authentication.Cookies var builder1 = new WebApplicationBuilder() .Configure(app => { - app.UseCookieAuthentication(options => + app.UseCookieAuthentication(new CookieAuthenticationOptions { - options.TicketDataFormat = new TicketDataFormat(dp); - options.CookieName = "Cookie"; + TicketDataFormat = new TicketDataFormat(dp), + CookieName = "Cookie" }); app.Use((context, next) => context.Authentication.SignInAsync("Cookies", @@ -1073,11 +1102,11 @@ namespace Microsoft.AspNet.Authentication.Cookies var builder2 = new WebApplicationBuilder() .Configure(app => { - app.UseCookieAuthentication(options => + app.UseCookieAuthentication(new CookieAuthenticationOptions { - options.AuthenticationScheme = "Cookies"; - options.CookieName = "Cookie"; - options.TicketDataFormat = new TicketDataFormat(dp); + AuthenticationScheme = "Cookies", + CookieName = "Cookie", + TicketDataFormat = new TicketDataFormat(dp) }); app.Use(async (context, next) => { @@ -1131,12 +1160,12 @@ namespace Microsoft.AspNet.Authentication.Cookies return me; } - private static TestServer CreateServer(Action configureOptions, Func testpath = null, Uri baseAddress = null, Action claimsTransform = null) + private static TestServer CreateServer(CookieAuthenticationOptions options, Func testpath = null, Uri baseAddress = null, ClaimsTransformationOptions claimsTransform = null) { var builder = new WebApplicationBuilder() .Configure(app => { - app.UseCookieAuthentication(configureOptions); + app.UseCookieAuthentication(options); // app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie2" }); if (claimsTransform != null) diff --git a/test/Microsoft.AspNet.Authentication.Test/Facebook/FacebookMiddlewareTests.cs b/test/Microsoft.AspNet.Authentication.Test/Facebook/FacebookMiddlewareTests.cs index 5263dadb57..95dcb2e5b7 100644 --- a/test/Microsoft.AspNet.Authentication.Test/Facebook/FacebookMiddlewareTests.cs +++ b/test/Microsoft.AspNet.Authentication.Test/Facebook/FacebookMiddlewareTests.cs @@ -30,23 +30,23 @@ namespace Microsoft.AspNet.Authentication.Facebook var server = CreateServer( app => { - app.UseFacebookAuthentication(options => + app.UseFacebookAuthentication(new FacebookOptions { - options.AppId = "Test App Id"; - options.AppSecret = "Test App Secret"; - options.Events = new OAuthEvents + AppId = "Test App Id", + AppSecret = "Test App Secret", + Events = new OAuthEvents { OnRedirectToAuthorizationEndpoint = context => { context.Response.Redirect(context.RedirectUri + "&custom=test"); return Task.FromResult(0); } - }; + } }); - app.UseCookieAuthentication(options => + app.UseCookieAuthentication(new CookieAuthenticationOptions { - options.AuthenticationScheme = "External"; - options.AutomaticAuthenticate = true; + AuthenticationScheme = "External", + AutomaticAuthenticate = true }); }, services => @@ -73,11 +73,11 @@ namespace Microsoft.AspNet.Authentication.Facebook { var server = CreateServer(app => app.Map("/base", map => { - map.UseFacebookAuthentication(options => + map.UseFacebookAuthentication(new FacebookOptions { - options.AppId = "Test App Id"; - options.AppSecret = "Test App Secret"; - options.SignInScheme = "External"; + AppId = "Test App Id", + AppSecret = "Test App Secret", + SignInScheme = "External" }); 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( app => { - app.UseFacebookAuthentication(options => + app.UseFacebookAuthentication(new FacebookOptions { - options.AppId = "Test App Id"; - options.AppSecret = "Test App Secret"; - options.SignInScheme = "External"; + AppId = "Test App Id", + AppSecret = "Test App Secret", + SignInScheme = "External" }); 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( app => { - app.UseFacebookAuthentication(options => + app.UseFacebookAuthentication(new FacebookOptions { - options.AppId = "Test App Id"; - options.AppSecret = "Test App Secret"; + AppId = "Test App Id", + AppSecret = "Test App Secret" + }); + app.UseCookieAuthentication(new CookieAuthenticationOptions + { + AuthenticationScheme = "External" }); - app.UseCookieAuthentication(options => options.AuthenticationScheme = "External"); }, services => { @@ -165,13 +168,13 @@ namespace Microsoft.AspNet.Authentication.Facebook app => { app.UseCookieAuthentication(); - app.UseFacebookAuthentication(options => + app.UseFacebookAuthentication(new FacebookOptions { - options.AppId = "Test App Id"; - options.AppSecret = "Test App Secret"; - options.StateDataFormat = stateFormat; - options.UserInformationEndpoint = customUserInfoEndpoint; - options.BackchannelHttpHandler = new TestHttpMessageHandler + AppId = "Test App Id", + AppSecret = "Test App Secret", + StateDataFormat = stateFormat, + UserInformationEndpoint = customUserInfoEndpoint, + BackchannelHttpHandler = new TestHttpMessageHandler { Sender = req => { @@ -200,7 +203,7 @@ namespace Microsoft.AspNet.Authentication.Facebook } return null; } - }; + } }); }, services => diff --git a/test/Microsoft.AspNet.Authentication.Test/Google/GoogleMiddlewareTests.cs b/test/Microsoft.AspNet.Authentication.Test/Google/GoogleMiddlewareTests.cs index dcfe91e5a1..6a6f028282 100644 --- a/test/Microsoft.AspNet.Authentication.Test/Google/GoogleMiddlewareTests.cs +++ b/test/Microsoft.AspNet.Authentication.Test/Google/GoogleMiddlewareTests.cs @@ -28,10 +28,10 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task ChallengeWillTriggerRedirection() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; + ClientId = "Test Id", + ClientSecret = "Test Secret" }); var transaction = await server.SendAsync("https://example.com/challenge"); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); @@ -50,10 +50,10 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task SignInThrows() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; + ClientId = "Test Id", + ClientSecret = "Test Secret" }); var transaction = await server.SendAsync("https://example.com/signIn"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); @@ -62,10 +62,10 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task SignOutThrows() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; + ClientId = "Test Id", + ClientSecret = "Test Secret" }); var transaction = await server.SendAsync("https://example.com/signOut"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); @@ -74,10 +74,10 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task ForbidThrows() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; + ClientId = "Test Id", + ClientSecret = "Test Secret" }); var transaction = await server.SendAsync("https://example.com/signOut"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); @@ -86,11 +86,11 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task Challenge401WillTriggerRedirection() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; - options.AutomaticChallenge = true; + ClientId = "Test Id", + ClientSecret = "Test Secret", + AutomaticChallenge = true }); var transaction = await server.SendAsync("https://example.com/401"); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); @@ -105,10 +105,10 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task ChallengeWillSetCorrelationCookie() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; + ClientId = "Test Id", + ClientSecret = "Test Secret" }); var transaction = await server.SendAsync("https://example.com/challenge"); Assert.Contains(".AspNet.Correlation.Google=", transaction.SetCookie.Single()); @@ -117,11 +117,11 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task Challenge401WillSetCorrelationCookie() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; - options.AutomaticChallenge = true; + ClientId = "Test Id", + ClientSecret = "Test Secret", + AutomaticChallenge = true }); var transaction = await server.SendAsync("https://example.com/401"); Assert.Contains(".AspNet.Correlation.Google=", transaction.SetCookie.Single()); @@ -130,10 +130,10 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task ChallengeWillSetDefaultScope() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; + ClientId = "Test Id", + ClientSecret = "Test Secret" }); var transaction = await server.SendAsync("https://example.com/challenge"); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); @@ -144,11 +144,11 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task Challenge401WillSetDefaultScope() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; - options.AutomaticChallenge = true; + ClientId = "Test Id", + ClientSecret = "Test Secret", + AutomaticChallenge = true }); var transaction = await server.SendAsync("https://example.com/401"); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); @@ -159,11 +159,11 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task ChallengeWillUseAuthenticationPropertiesAsParameters() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; - options.AutomaticChallenge = true; + ClientId = "Test Id", + ClientSecret = "Test Secret", + AutomaticChallenge = true }, context => { @@ -195,18 +195,18 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task ChallengeWillTriggerApplyRedirectEvent() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; - options.Events = new OAuthEvents + ClientId = "Test Id", + ClientSecret = "Test Secret", + Events = new OAuthEvents { OnRedirectToAuthorizationEndpoint = context => { context.Response.Redirect(context.RedirectUri + "&custom=test"); return Task.FromResult(0); } - }; + } }); var transaction = await server.SendAsync("https://example.com/challenge"); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); @@ -217,10 +217,10 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task AuthenticateWillFail() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; + ClientId = "Test Id", + ClientSecret = "Test Secret" }, async context => { @@ -240,10 +240,10 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task ReplyPathWithoutStateQueryStringWillBeRejected() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; + ClientId = "Test Id", + ClientSecret = "Test Secret" }); var error = await Assert.ThrowsAnyAsync(() => server.SendAsync("https://example.com/signin-google?code=TestCode")); Assert.Equal("The oauth state was missing or invalid.", error.GetBaseException().Message); @@ -254,22 +254,19 @@ namespace Microsoft.AspNet.Authentication.Google [InlineData(false)] public async Task ReplyPathWithErrorFails(bool redirect) { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; - if (redirect) + ClientId = "Test Id", + ClientSecret = "Test Secret", + 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(); - return Task.FromResult(0); - } - }; - } + ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message)); + 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"); if (redirect) @@ -291,13 +288,13 @@ namespace Microsoft.AspNet.Authentication.Google public async Task ReplyPathWillAuthenticateValidAuthorizeCodeAndState(string claimsIssuer) { var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; - options.StateDataFormat = stateFormat; - options.ClaimsIssuer = claimsIssuer; - options.BackchannelHttpHandler = new TestHttpMessageHandler + ClientId = "Test Id", + ClientSecret = "Test Secret", + StateDataFormat = stateFormat, + ClaimsIssuer = claimsIssuer, + BackchannelHttpHandler = new TestHttpMessageHandler { Sender = req => { @@ -335,7 +332,7 @@ namespace Microsoft.AspNet.Authentication.Google throw new NotImplementedException(req.RequestUri.AbsoluteUri); } - }; + } }); var properties = new AuthenticationProperties(); var correlationKey = ".AspNet.Correlation.Google"; @@ -373,31 +370,28 @@ namespace Microsoft.AspNet.Authentication.Google public async Task ReplyPathWillThrowIfCodeIsInvalid(bool redirect) { var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; - options.StateDataFormat = stateFormat; - options.BackchannelHttpHandler = new TestHttpMessageHandler + ClientId = "Test Id", + ClientSecret = "Test Secret", + StateDataFormat = stateFormat, + BackchannelHttpHandler = new TestHttpMessageHandler { Sender = req => { - return ReturnJsonResponse(new { Error = "Error" }, + return ReturnJsonResponse(new { Error = "Error" }, 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(); - return Task.FromResult(0); - } - }; - } + ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message)); + ctx.HandleResponse(); + return Task.FromResult(0); + } + } : new OAuthEvents() }); var properties = new AuthenticationProperties(); var correlationKey = ".AspNet.Correlation.Google"; @@ -429,30 +423,27 @@ namespace Microsoft.AspNet.Authentication.Google public async Task ReplyPathWillRejectIfAccessTokenIsMissing(bool redirect) { var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; - options.StateDataFormat = stateFormat; - options.BackchannelHttpHandler = new TestHttpMessageHandler + ClientId = "Test Id", + ClientSecret = "Test Secret", + StateDataFormat = stateFormat, + BackchannelHttpHandler = new TestHttpMessageHandler { Sender = req => { 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(); - return Task.FromResult(0); - } - }; - } + ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message)); + ctx.HandleResponse(); + return Task.FromResult(0); + } + } : new OAuthEvents() }); var properties = new AuthenticationProperties(); var correlationKey = ".AspNet.Correlation.Google"; @@ -481,12 +472,12 @@ namespace Microsoft.AspNet.Authentication.Google public async Task AuthenticatedEventCanGetRefreshToken() { var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; - options.StateDataFormat = stateFormat; - options.BackchannelHttpHandler = new TestHttpMessageHandler + ClientId = "Test Id", + ClientSecret = "Test Secret", + StateDataFormat = stateFormat, + BackchannelHttpHandler = new TestHttpMessageHandler { Sender = req => { @@ -525,8 +516,8 @@ namespace Microsoft.AspNet.Authentication.Google throw new NotImplementedException(req.RequestUri.AbsoluteUri); } - }; - options.Events = new OAuthEvents + }, + Events = new OAuthEvents { 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")); return Task.FromResult(0); } - }; + } }); var properties = new AuthenticationProperties(); var correlationKey = ".AspNet.Correlation.Google"; @@ -561,12 +552,12 @@ namespace Microsoft.AspNet.Authentication.Google public async Task NullRedirectUriWillRedirectToSlash() { var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; - options.StateDataFormat = stateFormat; - options.BackchannelHttpHandler = new TestHttpMessageHandler + ClientId = "Test Id", + ClientSecret = "Test Secret", + StateDataFormat = stateFormat, + BackchannelHttpHandler = new TestHttpMessageHandler { Sender = req => { @@ -605,15 +596,15 @@ namespace Microsoft.AspNet.Authentication.Google throw new NotImplementedException(req.RequestUri.AbsoluteUri); } - }; - options.Events = new OAuthEvents + }, + Events = new OAuthEvents { OnTicketReceived = context => { context.Ticket.Properties.RedirectUri = null; return Task.FromResult(0); } - }; + } }); var properties = new AuthenticationProperties(); var correlationKey = ".AspNet.Correlation.Google"; @@ -634,13 +625,13 @@ namespace Microsoft.AspNet.Authentication.Google public async Task ValidateAuthenticatedContext() { var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; - options.StateDataFormat = stateFormat; - options.AccessType = "offline"; - options.Events = new OAuthEvents() + ClientId = "Test Id", + ClientSecret = "Test Secret", + StateDataFormat = stateFormat, + AccessType = "offline", + Events = new OAuthEvents() { OnCreatingTicket = context => { @@ -655,8 +646,8 @@ namespace Microsoft.AspNet.Authentication.Google Assert.Equal(GoogleHelper.GetGivenName(context.User), "Test Given Name"); return Task.FromResult(0); } - }; - options.BackchannelHttpHandler = new TestHttpMessageHandler + }, + BackchannelHttpHandler = new TestHttpMessageHandler { Sender = req => { @@ -695,7 +686,7 @@ namespace Microsoft.AspNet.Authentication.Google throw new NotImplementedException(req.RequestUri.AbsoluteUri); } - }; + } }); var properties = new AuthenticationProperties(); @@ -717,10 +708,10 @@ namespace Microsoft.AspNet.Authentication.Google [Fact] public async Task NoStateCausesException() { - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; + ClientId = "Test Id", + ClientSecret = "Test Secret" }); //Post a message to the Google middleware @@ -732,11 +723,11 @@ namespace Microsoft.AspNet.Authentication.Google public async Task CanRedirectOnError() { var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest")); - var server = CreateServer(options => + var server = CreateServer(new GoogleOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; - options.Events = new OAuthEvents() + ClientId = "Test Id", + ClientSecret = "Test Secret", + Events = new OAuthEvents() { OnRemoteFailure = ctx => { @@ -744,7 +735,7 @@ namespace Microsoft.AspNet.Authentication.Google ctx.HandleResponse(); return Task.FromResult(0); } - }; + } }); //Post a message to the Google middleware @@ -764,17 +755,17 @@ namespace Microsoft.AspNet.Authentication.Google return res; } - private static TestServer CreateServer(Action configureOptions, Func testpath = null) + private static TestServer CreateServer(GoogleOptions options, Func testpath = null) { var builder = new WebApplicationBuilder() .Configure(app => { - app.UseCookieAuthentication(options => + app.UseCookieAuthentication(new CookieAuthenticationOptions { - options.AuthenticationScheme = TestExtensions.CookieAuthenticationScheme; - options.AutomaticAuthenticate = true; + AuthenticationScheme = TestExtensions.CookieAuthenticationScheme, + AutomaticAuthenticate = true }); - app.UseGoogleAuthentication(configureOptions); + app.UseGoogleAuthentication(options); app.UseClaimsTransformation(p => { var id = new ClaimsIdentity("xform"); @@ -833,7 +824,7 @@ namespace Microsoft.AspNet.Authentication.Google }) .ConfigureServices(services => { - services.AddAuthentication(options => options.SignInScheme = TestExtensions.CookieAuthenticationScheme); + services.AddAuthentication(authOptions => authOptions.SignInScheme = TestExtensions.CookieAuthenticationScheme); }); return new TestServer(builder); } diff --git a/test/Microsoft.AspNet.Authentication.Test/JwtBearer/JwtBearerMiddlewareTests.cs b/test/Microsoft.AspNet.Authentication.Test/JwtBearer/JwtBearerMiddlewareTests.cs index a3e7fbd54e..2732d0caaa 100644 --- a/test/Microsoft.AspNet.Authentication.Test/JwtBearer/JwtBearerMiddlewareTests.cs +++ b/test/Microsoft.AspNet.Authentication.Test/JwtBearer/JwtBearerMiddlewareTests.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Collections.Generic; using System.Net; using System.Net.Http; 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 public async Task BearerTokenValidation() { - var server = CreateServer(options => + var options = new JwtBearerOptions { - options.AutomaticAuthenticate = true; - - options.Authority = "https://login.windows.net/tushartest.onmicrosoft.com"; - options.Audience = "https://TusharTest.onmicrosoft.com/TodoListService-ManualJwt"; - options.TokenValidationParameters.ValidateLifetime = false; - }); + AutomaticAuthenticate = true, + Authority = "https://login.windows.net/tushartest.onmicrosoft.com", + Audience = "https://TusharTest.onmicrosoft.com/TodoListService-ManualJwt" + }; + options.TokenValidationParameters.ValidateLifetime = false; + var server = CreateServer(options); 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); @@ -44,9 +45,9 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] 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"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); @@ -55,9 +56,9 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] 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"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); @@ -67,11 +68,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task CustomHeaderReceived() { - var server = CreateServer(options => + var server = CreateServer(new JwtBearerOptions { - options.AutomaticAuthenticate = true; - - options.Events = new JwtBearerEvents() + AutomaticAuthenticate = true, + Events = new JwtBearerEvents() { OnReceivingToken = context => { @@ -90,7 +90,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer return Task.FromResult(null); } - }; + } }); var response = await SendAsync(server, "http://example.com/oauth", "someHeader someblob"); @@ -101,7 +101,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task NoHeaderReceived() { - var server = CreateServer(options => { }); + var server = CreateServer(new JwtBearerOptions()); var response = await SendAsync(server, "http://example.com/oauth"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); } @@ -109,7 +109,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task HeaderWithoutBearerReceived() { - var server = CreateServer(options => { }); + var server = CreateServer(new JwtBearerOptions()); var response = await SendAsync(server, "http://example.com/oauth","Token"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); } @@ -117,9 +117,9 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] 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"); @@ -130,12 +130,13 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task InvalidTokenReceived() { - var server = CreateServer(options => + var options = new JwtBearerOptions { - options.AutomaticAuthenticate = true; - options.SecurityTokenValidators.Clear(); - options.SecurityTokenValidators.Add(new InvalidTokenValidator()); - }); + AutomaticAuthenticate = true + }; + options.SecurityTokenValidators.Clear(); + options.SecurityTokenValidators.Add(new InvalidTokenValidator()); + var server = CreateServer(options); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); @@ -145,11 +146,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task CustomTokenReceived() { - var server = CreateServer(options => + var server = CreateServer(new JwtBearerOptions { - options.AutomaticAuthenticate = true; - - options.Events = new JwtBearerEvents() + AutomaticAuthenticate = true, + Events = new JwtBearerEvents() { OnReceivedToken = context => { @@ -168,7 +168,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer return Task.FromResult(null); } - }; + } }); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); @@ -179,11 +179,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task CustomTokenValidated() { - var server = CreateServer(options => + var options = new JwtBearerOptions { - options.AutomaticAuthenticate = true; - - options.Events = new JwtBearerEvents() + AutomaticAuthenticate = true, + Events = new JwtBearerEvents() { OnValidatedToken = context => { @@ -203,10 +202,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer return Task.FromResult(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"); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); @@ -216,11 +215,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task RetrievingTokenFromAlternateLocation() { - var server = CreateServer(options => + var server = CreateServer(new JwtBearerOptions { - options.AutomaticAuthenticate = true; - - options.Events = new JwtBearerEvents() + AutomaticAuthenticate = true, + Events = new JwtBearerEvents() { OnReceivingToken = context => { @@ -244,7 +242,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer return Task.FromResult(null); } - }; + } }); var response = await SendAsync(server, "http://example.com/oauth", "Bearer Token"); @@ -255,9 +253,9 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task BearerTurns401To403IfAuthenticated() { - var server = CreateServer(options => + var server = CreateServer(new JwtBearerOptions { - options.Events = new JwtBearerEvents() + Events = new JwtBearerEvents() { OnReceivedToken = context => { @@ -276,7 +274,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer return Task.FromResult(null); } - }; + } }); var response = await SendAsync(server, "http://example.com/unauthorized", "Bearer Token"); @@ -286,9 +284,9 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task BearerDoesNothingTo401IfNotAuthenticated() { - var server = CreateServer(options => + var server = CreateServer(new JwtBearerOptions { - options.Events = new JwtBearerEvents() + Events = new JwtBearerEvents() { OnReceivedToken = context => { @@ -307,7 +305,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer return Task.FromResult(null); } - }; + } }); var response = await SendAsync(server, "http://example.com/unauthorized"); @@ -317,11 +315,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task EventOnReceivingTokenSkipped_NoMoreEventsExecuted() { - var server = CreateServer(options => + var server = CreateServer(new JwtBearerOptions { - options.AutomaticAuthenticate = true; - - options.Events = new JwtBearerEvents() + AutomaticAuthenticate = true, + Events = new JwtBearerEvents() { OnReceivingToken = context => { @@ -344,7 +341,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer { throw new NotImplementedException(); }, - }; + } }); var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token"); @@ -355,11 +352,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task EventOnReceivedTokenSkipped_NoMoreEventsExecuted() { - var server = CreateServer(options => + var server = CreateServer(new JwtBearerOptions { - options.AutomaticAuthenticate = true; - - options.Events = new JwtBearerEvents() + AutomaticAuthenticate = true, + Events = new JwtBearerEvents() { OnReceivedToken = context => { @@ -378,7 +374,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer { throw new NotImplementedException(); }, - }; + } }); var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token"); @@ -389,12 +385,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task EventOnValidatedTokenSkipped_NoMoreEventsExecuted() { - var server = CreateServer(options => + var options = new JwtBearerOptions { - options.AutomaticAuthenticate = true; - options.SecurityTokenValidators.Clear(); - options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT")); - options.Events = new JwtBearerEvents() + AutomaticAuthenticate = true, + Events = new JwtBearerEvents() { OnValidatedToken = context => { @@ -409,8 +403,11 @@ namespace Microsoft.AspNet.Authentication.JwtBearer { 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"); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); @@ -420,12 +417,10 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task EventOnAuthenticationFailedSkipped_NoMoreEventsExecuted() { - var server = CreateServer(options => + var options = new JwtBearerOptions { - options.AutomaticAuthenticate = true; - options.SecurityTokenValidators.Clear(); - options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT")); - options.Events = new JwtBearerEvents() + AutomaticAuthenticate = true, + Events = new JwtBearerEvents() { OnValidatedToken = context => { @@ -440,8 +435,11 @@ namespace Microsoft.AspNet.Authentication.JwtBearer { 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"); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); @@ -451,18 +449,18 @@ namespace Microsoft.AspNet.Authentication.JwtBearer [Fact] public async Task EventOnChallengeSkipped_ResponseNotModified() { - var server = CreateServer(options => + var server = CreateServer(new JwtBearerOptions { - options.AutomaticAuthenticate = true; - options.AutomaticChallenge = true; - options.Events = new JwtBearerEvents() + AutomaticAuthenticate = true, + AutomaticChallenge = true, + Events = new JwtBearerEvents() { OnChallenge = context => { context.SkipToNextMiddleware(); return Task.FromResult(0); }, - }; + } }); 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 configureOptions, Func handler = null) + private static TestServer CreateServer(JwtBearerOptions options, Func handler = null) { var builder = new WebApplicationBuilder() .Configure(app => { - if (configureOptions != null) + if (options != null) { - app.UseJwtBearerAuthentication(configureOptions); + app.UseJwtBearerAuthentication(options); } app.Use(async (context, next) => diff --git a/test/Microsoft.AspNet.Authentication.Test/MicrosoftAccount/MicrosoftAccountMiddlewareTests.cs b/test/Microsoft.AspNet.Authentication.Test/MicrosoftAccount/MicrosoftAccountMiddlewareTests.cs index 849cdfe0a2..29f6e0edcc 100644 --- a/test/Microsoft.AspNet.Authentication.Test/MicrosoftAccount/MicrosoftAccountMiddlewareTests.cs +++ b/test/Microsoft.AspNet.Authentication.Test/MicrosoftAccount/MicrosoftAccountMiddlewareTests.cs @@ -8,7 +8,6 @@ using System.Security.Claims; using System.Text; using System.Text.Encodings.Web; using System.Threading.Tasks; -using Microsoft.AspNet.Authentication.MicrosoftAccount; using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Builder; using Microsoft.AspNet.DataProtection; @@ -27,19 +26,18 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount [Fact] public async Task ChallengeWillTriggerApplyRedirectEvent() { - var server = CreateServer( - options => + var server = CreateServer(new MicrosoftAccountOptions { - options.ClientId = "Test Client Id"; - options.ClientSecret = "Test Client Secret"; - options.Events = new OAuthEvents + ClientId = "Test Client Id", + ClientSecret = "Test Client Secret", + Events = new OAuthEvents { OnRedirectToAuthorizationEndpoint = context => { context.Response.Redirect(context.RedirectUri + "&custom=test"); return Task.FromResult(0); } - }; + } }); var transaction = await server.SendAsync("http://example.com/challenge"); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); @@ -50,10 +48,10 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount [Fact] public async Task SignInThrows() { - var server = CreateServer(options => + var server = CreateServer(new MicrosoftAccountOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; + ClientId = "Test Id", + ClientSecret = "Test Secret" }); var transaction = await server.SendAsync("https://example.com/signIn"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); @@ -62,10 +60,10 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount [Fact] public async Task SignOutThrows() { - var server = CreateServer(options => + var server = CreateServer(new MicrosoftAccountOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; + ClientId = "Test Id", + ClientSecret = "Test Secret" }); var transaction = await server.SendAsync("https://example.com/signOut"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); @@ -74,10 +72,10 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount [Fact] public async Task ForbidThrows() { - var server = CreateServer(options => + var server = CreateServer(new MicrosoftAccountOptions { - options.ClientId = "Test Id"; - options.ClientSecret = "Test Secret"; + ClientId = "Test Id", + ClientSecret = "Test Secret" }); var transaction = await server.SendAsync("https://example.com/signOut"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); @@ -86,11 +84,10 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount [Fact] public async Task ChallengeWillTriggerRedirection() { - var server = CreateServer( - options => - { - options.ClientId = "Test Client Id"; - options.ClientSecret = "Test Client Secret"; + var server = CreateServer(new MicrosoftAccountOptions + { + ClientId = "Test Client Id", + ClientSecret = "Test Client Secret" }); var transaction = await server.SendAsync("http://example.com/challenge"); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); @@ -107,13 +104,12 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount public async Task AuthenticatedEventCanGetRefreshToken() { var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("MsftTest")); - var server = CreateServer( - options => - { - options.ClientId = "Test Client Id"; - options.ClientSecret = "Test Client Secret"; - options.StateDataFormat = stateFormat; - options.BackchannelHttpHandler = new TestHttpMessageHandler + var server = CreateServer(new MicrosoftAccountOptions + { + ClientId = "Test Client Id", + ClientSecret = "Test Client Secret", + StateDataFormat = stateFormat, + BackchannelHttpHandler = new TestHttpMessageHandler { Sender = req => { @@ -144,8 +140,8 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount return null; } - }; - options.Events = new OAuthEvents + }, + Events = new OAuthEvents { 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")); return Task.FromResult(null); } - }; + } }); var properties = new AuthenticationProperties(); var correlationKey = ".AspNet.Correlation.Microsoft"; @@ -176,17 +172,17 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount Assert.Equal("Test Refresh Token", transaction.FindClaimValue("RefreshToken")); } - private static TestServer CreateServer(Action configureOptions) + private static TestServer CreateServer(MicrosoftAccountOptions options) { var builder = new WebApplicationBuilder() .Configure(app => { - app.UseCookieAuthentication(options => + app.UseCookieAuthentication(new CookieAuthenticationOptions { - options.AuthenticationScheme = TestExtensions.CookieAuthenticationScheme; - options.AutomaticAuthenticate = true; + AuthenticationScheme = TestExtensions.CookieAuthenticationScheme, + AutomaticAuthenticate = true }); - app.UseMicrosoftAccountAuthentication(configureOptions); + app.UseMicrosoftAccountAuthentication(options); app.Use(async (context, next) => { @@ -221,9 +217,9 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount .ConfigureServices(services => { services.AddAuthentication(); - services.Configure(options => + services.Configure(authOptions => { - options.SignInScheme = TestExtensions.CookieAuthenticationScheme; + authOptions.SignInScheme = TestExtensions.CookieAuthenticationScheme; }); }); return new TestServer(builder); diff --git a/test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectHandlerTests.cs b/test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectHandlerTests.cs index 801cc71f95..0166c13e48 100644 --- a/test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectHandlerTests.cs +++ b/test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectHandlerTests.cs @@ -15,6 +15,7 @@ using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Tokens; using Xunit; @@ -31,20 +32,20 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect private const string ExpectedStateParameter = "expectedState"; [Theory, MemberData(nameof(AuthenticateCoreStateDataSet))] - public async Task AuthenticateCoreState(Action action, OpenIdConnectMessage message) + public async Task AuthenticateCoreState(OpenIdConnectOptions option, OpenIdConnectMessage message) { 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))); } - public static TheoryData, OpenIdConnectMessage> AuthenticateCoreStateDataSet + public static TheoryData AuthenticateCoreStateDataSet { get { var formater = new AuthenticationPropertiesFormaterKeyValue(); var properties = new AuthenticationProperties(); - var dataset = new TheoryData, OpenIdConnectMessage>(); + var dataset = new TheoryData(); // expected user state is added to the message.Parameters.Items[ExpectedStateParameter] // Userstate == null @@ -52,7 +53,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect message.State = UrlEncoder.Default.Encode(formater.Protect(properties)); message.Code = Guid.NewGuid().ToString(); message.Parameters.Add(ExpectedStateParameter, null); - dataset.Add(SetStateOptions, message); + dataset.Add(GetStateOptions(), message); // Userstate != null message = new OpenIdConnectMessage(); @@ -62,15 +63,16 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect properties.Items.Add(OpenIdConnectDefaults.UserstatePropertiesKey, userstate); message.State = UrlEncoder.Default.Encode(formater.Protect(properties)); message.Parameters.Add(ExpectedStateParameter, userstate); - dataset.Add(SetStateOptions, message); + dataset.Add(GetStateOptions(), message); return dataset; } } // Setup an event to check for expected state. // 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.ConfigurationManager = TestUtilities.DefaultOpenIdConnectConfigurationManager; options.ClientId = Guid.NewGuid().ToString(); @@ -91,16 +93,15 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect return Task.FromResult(null); } }; + return options; } - private static TestServer CreateServer(Action configureOptions, UrlEncoder encoder, OpenIdConnectHandler handler = null) + private static TestServer CreateServer(OpenIdConnectOptions options, UrlEncoder encoder, OpenIdConnectHandler handler = null) { var builder = new WebApplicationBuilder() .Configure(app => { - var options = new OpenIdConnectOptions(); - configureOptions(options); - app.UseMiddleware(options, encoder, handler); + app.UseMiddleware(Options.Create(options), encoder, handler); app.Use(async (context, next) => { await next(); diff --git a/test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectMiddlewareForTestingAuthenticate.cs b/test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectMiddlewareForTestingAuthenticate.cs index 2a91eecdbc..c73cf8f942 100644 --- a/test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectMiddlewareForTestingAuthenticate.cs +++ b/test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectMiddlewareForTestingAuthenticate.cs @@ -4,6 +4,7 @@ using System; using System.Text.Encodings.Web; using Microsoft.AspNet.Authentication.OpenIdConnect; +using Microsoft.AspNet.Builder; using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.Http; using Microsoft.Extensions.Logging; @@ -27,7 +28,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect UrlEncoder encoder, IServiceProvider services, IOptions sharedOptions, - OpenIdConnectOptions options, + IOptions options, HtmlEncoder htmlEncoder, OpenIdConnectHandler handler = null ) diff --git a/test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectMiddlewareTests.cs b/test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectMiddlewareTests.cs index 9446be945a..992f7b9c90 100644 --- a/test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectMiddlewareTests.cs +++ b/test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectMiddlewareTests.cs @@ -42,12 +42,12 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect [Fact] public async Task ChallengeWillIssueHtmlFormWhenEnabled() { - var server = CreateServer(options => + var server = CreateServer(new OpenIdConnectOptions { - options.Authority = DefaultAuthority; - options.ClientId = "Test Id"; - options.Configuration = TestUtilities.DefaultOpenIdConnectConfiguration; - options.AuthenticationMethod = OpenIdConnectRedirectBehavior.FormPost; + Authority = DefaultAuthority, + ClientId = "Test Id", + Configuration = TestUtilities.DefaultOpenIdConnectConfiguration, + AuthenticationMethod = OpenIdConnectRedirectBehavior.FormPost }); var transaction = await SendAsync(server, DefaultHost + Challenge); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); @@ -61,10 +61,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect var stateDataFormat = new AuthenticationPropertiesFormaterKeyValue(); var queryValues = ExpectedQueryValues.Defaults(DefaultAuthority); queryValues.State = OpenIdConnectDefaults.AuthenticationPropertiesKey + "=" + stateDataFormat.Protect(new AuthenticationProperties()); - var server = CreateServer(options => - { - SetOptions(options, DefaultParameters(), queryValues); - }); + var server = CreateServer(GetOptions(DefaultParameters(), queryValues)); var transaction = await SendAsync(server, DefaultHost + Challenge); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); @@ -74,11 +71,11 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect [Fact] public async Task ChallengeWillSetNonceAndStateCookies() { - var server = CreateServer(options => + var server = CreateServer(new OpenIdConnectOptions { - options.Authority = DefaultAuthority; - options.ClientId = "Test Id"; - options.Configuration = TestUtilities.DefaultOpenIdConnectConfiguration; + Authority = DefaultAuthority, + ClientId = "Test Id", + Configuration = TestUtilities.DefaultOpenIdConnectConfiguration }); var transaction = await SendAsync(server, DefaultHost + Challenge); @@ -95,10 +92,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect public async Task ChallengeWillUseOptionsProperties() { var queryValues = new ExpectedQueryValues(DefaultAuthority); - var server = CreateServer(options => - { - SetOptions(options, DefaultParameters(), queryValues); - }); + var server = CreateServer(GetOptions(DefaultParameters(), queryValues)); var transaction = await SendAsync(server, DefaultHost + Challenge); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); @@ -121,7 +115,7 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect { RequestType = OpenIdConnectRequestType.AuthenticationRequest }; - var server = CreateServer(SetProtocolMessageOptions); + var server = CreateServer(GetProtocolMessageOptions()); var transaction = await SendAsync(server, DefaultHost + Challenge); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); queryValues.CheckValues(transaction.Response.Headers.Location.AbsoluteUri, new string[] {}); @@ -143,14 +137,15 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect { RequestType = OpenIdConnectRequestType.LogoutRequest }; - var server = CreateServer(SetProtocolMessageOptions); + var server = CreateServer(GetProtocolMessageOptions()); var transaction = await SendAsync(server, DefaultHost + Signout); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); 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); options.AutomaticChallenge = true; options.Events = new OpenIdConnectEvents() @@ -166,7 +161,9 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect return Task.FromResult(0); } }; + return options; } + private class FakeOpenIdConnectMessage : OpenIdConnectMessage { private readonly string _authorizeRequest; @@ -207,21 +204,19 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect 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); - options.AutomaticChallenge = challenge.Equals(ChallengeWithOutContext); - options.Events = new OpenIdConnectEvents() + OnRedirectToAuthenticationEndpoint = context => { - OnRedirectToAuthenticationEndpoint = context => - { - context.ProtocolMessage.State = userState; - context.ProtocolMessage.RedirectUri = queryValues.RedirectUri; - return Task.FromResult(null); - } + context.ProtocolMessage.State = userState; + context.ProtocolMessage.RedirectUri = queryValues.RedirectUri; + return Task.FromResult(null); + } - }; - }, null, properties); + }; + var server = CreateServer(options, null, properties); var transaction = await SendAsync(server, DefaultHost + challenge); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); @@ -260,29 +255,28 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect { var queryValues = 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); - options.Events = new OpenIdConnectEvents() + OnRedirectToAuthenticationEndpoint = context => { - OnRedirectToAuthenticationEndpoint = context => - { - context.ProtocolMessage.ClientId = queryValuesSetInEvent.ClientId; - context.ProtocolMessage.RedirectUri = queryValuesSetInEvent.RedirectUri; - context.ProtocolMessage.Resource = queryValuesSetInEvent.Resource; - context.ProtocolMessage.Scope = queryValuesSetInEvent.Scope; - return Task.FromResult(null); - } - }; - }); + context.ProtocolMessage.ClientId = queryValuesSetInEvent.ClientId; + context.ProtocolMessage.RedirectUri = queryValuesSetInEvent.RedirectUri; + context.ProtocolMessage.Resource = queryValuesSetInEvent.Resource; + context.ProtocolMessage.Scope = queryValuesSetInEvent.Scope; + return Task.FromResult(null); + } + }; + var server = CreateServer(options); var transaction = await SendAsync(server, DefaultHost + Challenge); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); queryValuesSetInEvent.CheckValues(transaction.Response.Headers.Location.AbsoluteUri, DefaultParameters()); } - private void SetOptions(OpenIdConnectOptions options, List parameters, ExpectedQueryValues queryValues, ISecureDataFormat secureDataFormat = null) + private OpenIdConnectOptions GetOptions(List parameters, ExpectedQueryValues queryValues, ISecureDataFormat secureDataFormat = null) { + var options = new OpenIdConnectOptions(); foreach (var param in parameters) { if (param.Equals(OpenIdConnectParameterNames.ClientId)) @@ -301,6 +295,8 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect options.Authority = queryValues.Authority; options.Configuration = queryValues.Configuration; options.StateDataFormat = secureDataFormat ?? new AuthenticationPropertiesFormaterKeyValue(); + + return options; } private List DefaultParameters(string[] additionalParams = null) @@ -333,11 +329,11 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect public async Task SignOutWithDefaultRedirectUri() { var configuration = TestUtilities.DefaultOpenIdConnectConfiguration; - var server = CreateServer(options => + var server = CreateServer(new OpenIdConnectOptions { - options.Authority = DefaultAuthority; - options.ClientId = "Test Id"; - options.Configuration = configuration; + Authority = DefaultAuthority, + ClientId = "Test Id", + Configuration = configuration }); var transaction = await SendAsync(server, DefaultHost + Signout); @@ -349,12 +345,12 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect public async Task SignOutWithCustomRedirectUri() { var configuration = TestUtilities.DefaultOpenIdConnectConfiguration; - var server = CreateServer(options => + var server = CreateServer(new OpenIdConnectOptions { - options.Authority = DefaultAuthority; - options.ClientId = "Test Id"; - options.Configuration = configuration; - options.PostLogoutRedirectUri = "https://example.com/logout"; + Authority = DefaultAuthority, + ClientId = "Test Id", + Configuration = configuration, + PostLogoutRedirectUri = "https://example.com/logout" }); 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() { var configuration = TestUtilities.DefaultOpenIdConnectConfiguration; - var server = CreateServer(options => + var server = CreateServer(new OpenIdConnectOptions { - options.Authority = DefaultAuthority; - options.ClientId = "Test Id"; - options.Configuration = configuration; - options.PostLogoutRedirectUri = "https://example.com/logout"; + Authority = DefaultAuthority, + ClientId = "Test Id", + Configuration = configuration, + PostLogoutRedirectUri = "https://example.com/logout" }); 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); } - private static TestServer CreateServer(Action configureOptions, Func handler = null, AuthenticationProperties properties = null) + private static TestServer CreateServer(OpenIdConnectOptions options, Func handler = null, AuthenticationProperties properties = null) { var builder = new WebApplicationBuilder() .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) => { var req = context.Request; @@ -434,9 +430,9 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect .ConfigureServices(services => { services.AddAuthentication(); - services.Configure(options => + services.Configure(authOptions => { - options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; + authOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }); }); return new TestServer(builder); diff --git a/test/Microsoft.AspNet.Authentication.Test/Twitter/TwitterMiddlewareTests.cs b/test/Microsoft.AspNet.Authentication.Test/Twitter/TwitterMiddlewareTests.cs index db77d7f5ff..2d00d617de 100644 --- a/test/Microsoft.AspNet.Authentication.Test/Twitter/TwitterMiddlewareTests.cs +++ b/test/Microsoft.AspNet.Authentication.Test/Twitter/TwitterMiddlewareTests.cs @@ -20,19 +20,19 @@ namespace Microsoft.AspNet.Authentication.Twitter [Fact] public async Task ChallengeWillTriggerApplyRedirectEvent() { - var server = CreateServer(options => + var server = CreateServer(new TwitterOptions { - options.ConsumerKey = "Test Consumer Key"; - options.ConsumerSecret = "Test Consumer Secret"; - options.Events = new TwitterEvents + ConsumerKey = "Test Consumer Key", + ConsumerSecret = "Test Consumer Secret", + Events = new TwitterEvents { OnRedirectToAuthorizationEndpoint = context => { context.Response.Redirect(context.RedirectUri + "&custom=test"); return Task.FromResult(0); } - }; - options.BackchannelHttpHandler = new TestHttpMessageHandler + }, + BackchannelHttpHandler = new TestHttpMessageHandler { Sender = req => { @@ -48,7 +48,7 @@ namespace Microsoft.AspNet.Authentication.Twitter } return null; } - }; + } }, context => { @@ -65,10 +65,10 @@ namespace Microsoft.AspNet.Authentication.Twitter [Fact] public async Task BadSignInWillThrow() { - var server = CreateServer(options => + var server = CreateServer(new TwitterOptions { - options.ConsumerKey = "Test Consumer Key"; - options.ConsumerSecret = "Test Consumer Secret"; + ConsumerKey = "Test Consumer Key", + ConsumerSecret = "Test Consumer Secret" }); // Send a bogus sign in @@ -79,10 +79,10 @@ namespace Microsoft.AspNet.Authentication.Twitter [Fact] public async Task SignInThrows() { - var server = CreateServer(options => + var server = CreateServer(new TwitterOptions { - options.ConsumerKey = "Test Consumer Key"; - options.ConsumerSecret = "Test Consumer Secret"; + ConsumerKey = "Test Consumer Key", + ConsumerSecret = "Test Consumer Secret" }); var transaction = await server.SendAsync("https://example.com/signIn"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); @@ -91,10 +91,10 @@ namespace Microsoft.AspNet.Authentication.Twitter [Fact] public async Task SignOutThrows() { - var server = CreateServer(options => + var server = CreateServer(new TwitterOptions { - options.ConsumerKey = "Test Consumer Key"; - options.ConsumerSecret = "Test Consumer Secret"; + ConsumerKey = "Test Consumer Key", + ConsumerSecret = "Test Consumer Secret" }); var transaction = await server.SendAsync("https://example.com/signOut"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); @@ -103,10 +103,10 @@ namespace Microsoft.AspNet.Authentication.Twitter [Fact] public async Task ForbidThrows() { - var server = CreateServer(options => + var server = CreateServer(new TwitterOptions { - options.ConsumerKey = "Test Consumer Key"; - options.ConsumerSecret = "Test Consumer Secret"; + ConsumerKey = "Test Consumer Key", + ConsumerSecret = "Test Consumer Secret" }); var transaction = await server.SendAsync("https://example.com/signOut"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); @@ -116,11 +116,11 @@ namespace Microsoft.AspNet.Authentication.Twitter [Fact] public async Task ChallengeWillTriggerRedirection() { - var server = CreateServer(options => - { - options.ConsumerKey = "Test Consumer Key"; - options.ConsumerSecret = "Test Consumer Secret"; - options.BackchannelHttpHandler = new TestHttpMessageHandler + var server = CreateServer(new TwitterOptions + { + ConsumerKey = "Test Consumer Key", + ConsumerSecret = "Test Consumer Secret", + BackchannelHttpHandler = new TestHttpMessageHandler { Sender = req => { @@ -136,7 +136,7 @@ namespace Microsoft.AspNet.Authentication.Twitter } return null; } - }; + } }, context => { @@ -150,16 +150,16 @@ namespace Microsoft.AspNet.Authentication.Twitter Assert.Contains("https://api.twitter.com/oauth/authenticate?oauth_token=", location); } - private static TestServer CreateServer(Action configure, Func handler = null) + private static TestServer CreateServer(TwitterOptions options, Func handler = null) { var builder = new WebApplicationBuilder() .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) => { var req = context.Request; @@ -185,9 +185,9 @@ namespace Microsoft.AspNet.Authentication.Twitter .ConfigureServices(services => { services.AddAuthentication(); - services.Configure(options => + services.Configure(authOptions => { - options.SignInScheme = "External"; + authOptions.SignInScheme = "External"; }); }); return new TestServer(builder); diff --git a/test/Microsoft.AspNet.Authorization.Test/DefaultAuthorizationServiceTests.cs b/test/Microsoft.AspNet.Authorization.Test/DefaultAuthorizationServiceTests.cs index f2b28f6aba..902bf17cea 100644 --- a/test/Microsoft.AspNet.Authorization.Test/DefaultAuthorizationServiceTests.cs +++ b/test/Microsoft.AspNet.Authorization.Test/DefaultAuthorizationServiceTests.cs @@ -19,6 +19,7 @@ namespace Microsoft.AspNet.Authorization.Test var services = new ServiceCollection(); services.AddAuthorization(); services.AddLogging(); + services.AddOptions(); if (setupServices != null) { setupServices(services); diff --git a/test/Microsoft.AspNet.CookiePolicy.Test/CookiePolicyTests.cs b/test/Microsoft.AspNet.CookiePolicy.Test/CookiePolicyTests.cs index 4b798c5613..d0639e627d 100644 --- a/test/Microsoft.AspNet.CookiePolicy.Test/CookiePolicyTests.cs +++ b/test/Microsoft.AspNet.CookiePolicy.Test/CookiePolicyTests.cs @@ -36,7 +36,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test public async Task SecureAlwaysSetsSecure() { await RunTest("/secureAlways", - options => options.Secure = SecurePolicy.Always, + new CookiePolicyOptions + { + Secure = SecurePolicy.Always + }, SecureCookieAppends, new RequestTest("http://example.com/secureAlways", transaction => @@ -53,7 +56,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test public async Task SecureNoneLeavesSecureUnchanged() { await RunTest("/secureNone", - options => options.Secure = SecurePolicy.None, + new CookiePolicyOptions + { + Secure = SecurePolicy.None + }, SecureCookieAppends, new RequestTest("http://example.com/secureNone", transaction => @@ -71,7 +77,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test public async Task SecureSameUsesRequest() { await RunTest("/secureSame", - options => options.Secure = SecurePolicy.SameAsRequest, + new CookiePolicyOptions + { + Secure = SecurePolicy.SameAsRequest + }, SecureCookieAppends, new RequestTest("http://example.com/secureSame", transaction => @@ -97,7 +106,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test public async Task HttpOnlyAlwaysSetsItAlways() { await RunTest("/httpOnlyAlways", - options => options.HttpOnly = HttpOnlyPolicy.Always, + new CookiePolicyOptions + { + HttpOnly = HttpOnlyPolicy.Always + }, HttpCookieAppends, new RequestTest("http://example.com/httpOnlyAlways", transaction => @@ -114,7 +126,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test public async Task HttpOnlyNoneLeavesItAlone() { await RunTest("/httpOnlyNone", - options => options.HttpOnly = HttpOnlyPolicy.None, + new CookiePolicyOptions + { + HttpOnly = HttpOnlyPolicy.None + }, HttpCookieAppends, new RequestTest("http://example.com/httpOnlyNone", transaction => @@ -133,7 +148,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test var builder = new WebApplicationBuilder() .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 => { context.Response.Cookies.Append("A", "A"); @@ -160,7 +178,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test var builder = new WebApplicationBuilder() .Configure(app => { - app.UseCookiePolicy(options => options.OnDeleteCookie = ctx => ctx.CookieName = "A"); + app.UseCookiePolicy(new CookiePolicyOptions + { + OnDeleteCookie = ctx => ctx.CookieName = "A" + }); app.Run(context => { context.Response.Cookies.Delete("A"); @@ -190,7 +211,10 @@ namespace Microsoft.AspNet.CookiePolicy.Test context.Features.Set(new TestCookieFeature()); return next(context); }); - app.UseCookiePolicy(options => options.OnDeleteCookie = ctx => ctx.CookieName = "A"); + app.UseCookiePolicy(new CookiePolicyOptions + { + OnDeleteCookie = ctx => ctx.CookieName = "A" + }); app.Run(context => { Assert.Throws(() => context.Response.Cookies.Delete("A")); @@ -254,7 +278,7 @@ namespace Microsoft.AspNet.CookiePolicy.Test private async Task RunTest( string path, - Action configureCookiePolicy, + CookiePolicyOptions cookiePolicy, RequestDelegate configureSetup, params RequestTest[] tests) { @@ -263,7 +287,7 @@ namespace Microsoft.AspNet.CookiePolicy.Test { app.Map(path, map => { - map.UseCookiePolicy(configureCookiePolicy); + map.UseCookiePolicy(cookiePolicy); map.Run(configureSetup); }); }); diff --git a/test/Microsoft.Owin.Security.Interop.Test/CookieInteropTests.cs b/test/Microsoft.Owin.Security.Interop.Test/CookieInteropTests.cs index 9ef81bc7f5..c7645a2874 100644 --- a/test/Microsoft.Owin.Security.Interop.Test/CookieInteropTests.cs +++ b/test/Microsoft.Owin.Security.Interop.Test/CookieInteropTests.cs @@ -38,7 +38,7 @@ namespace Microsoft.Owin.Security.Interop { app.Properties["host.AppName"] = "Microsoft.Owin.Security.Tests"; - app.UseCookieAuthentication(new CookieAuthenticationOptions + app.UseCookieAuthentication(new Cookies.CookieAuthenticationOptions { TicketDataFormat = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector)) }); @@ -55,7 +55,10 @@ namespace Microsoft.Owin.Security.Interop var builder = new WebApplicationBuilder() .Configure(app => { - app.UseCookieAuthentication(options => options.DataProtectionProvider = dataProtection); + app.UseCookieAuthentication(new AspNet.Builder.CookieAuthenticationOptions + { + DataProtectionProvider = dataProtection + }); app.Run(async context => { var result = await context.Authentication.AuthenticateAsync("Cookies"); @@ -88,7 +91,10 @@ namespace Microsoft.Owin.Security.Interop var builder = new WebApplicationBuilder() .Configure(app => { - app.UseCookieAuthentication(options => options.DataProtectionProvider = dataProtection); + app.UseCookieAuthentication(new AspNet.Builder.CookieAuthenticationOptions + { + DataProtectionProvider = dataProtection + }); app.Run(context => context.Authentication.SignInAsync("Cookies", user)); }) .ConfigureServices(services => services.AddAuthentication()); @@ -100,7 +106,7 @@ namespace Microsoft.Owin.Security.Interop { 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)) });