Updating to new options pattern

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

View File

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

View File

@ -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 =>

View File

@ -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

View File

@ -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 =>

View File

@ -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

View File

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

View File

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

View File

@ -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<CookieAuthenticationOptions> 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();

View File

@ -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
{
/// <summary>
/// Contains the options used by the CookiesAuthenticationMiddleware

View File

@ -2,9 +2,8 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Security.Claims;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;
namespace Microsoft.AspNet.Authentication.Cookies
{

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Security.Claims;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Security.Claims;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;

View File

@ -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;

View File

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

View File

@ -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"
},

View File

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

View File

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

View File

@ -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<SharedAuthenticationOptions> sharedOptions,
FacebookOptions options)
IOptions<FacebookOptions> options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
{
if (next == null)

View File

@ -2,10 +2,10 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
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
{
/// <summary>
/// Configuration options for <see cref="FacebookMiddleware"/>.

View File

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

View File

@ -7,8 +7,9 @@ using System.Net.Http;
using System.Net.Http.Headers;
using System.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;

View File

@ -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<SharedAuthenticationOptions> sharedOptions,
GoogleOptions options)
IOptions<GoogleOptions> options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
{
if (next == null)

View File

@ -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
{
/// <summary>
/// Configuration options for <see cref="GoogleMiddleware"/>.

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.JwtBearer

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.JwtBearer

View File

@ -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;

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <param name="configureOptions">An action delegate to configure the provided <see cref="JwtBearerOptions"/>.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseJwtBearerAuthentication(this IApplicationBuilder app, Action<JwtBearerOptions> configureOptions)
public static IApplicationBuilder UseJwtBearerAuthentication(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var options = new JwtBearerOptions();
configureOptions(options);
return app.UseMiddleware<JwtBearerMiddleware>(options);
return app.UseMiddleware<JwtBearerMiddleware>();
}
/// <summary>
@ -63,7 +56,7 @@ namespace Microsoft.AspNet.Builder
throw new ArgumentNullException(nameof(options));
}
return app.UseMiddleware<JwtBearerMiddleware>(options);
return app.UseMiddleware<JwtBearerMiddleware>(Options.Create(options));
}
}
}

View File

@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Linq;
using System.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;

View File

@ -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<JwtBearerOptions> options)
: base(next, options, loggerFactory, encoder)
{
if (next == null)

View File

@ -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
{
/// <summary>
/// Options class provides information needed to control Bearer Authentication middleware behavior

View File

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

View File

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

View File

@ -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<SharedAuthenticationOptions> sharedOptions,
MicrosoftAccountOptions options)
IOptions<MicrosoftAccountOptions> options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
{
if (next == null)

View File

@ -2,9 +2,9 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Authentication.MicrosoftAccount;
namespace Microsoft.AspNet.Authentication.MicrosoftAccount
namespace Microsoft.AspNet.Builder
{
/// <summary>
/// Configuration options for <see cref="MicrosoftAccountMiddleware"/>.

View File

@ -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

View File

@ -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;

View File

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

View File

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

View File

@ -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<SharedAuthenticationOptions> sharedOptions,
TOptions options)
IOptions<TOptions> options)
: base(next, options, loggerFactory, encoder)
{
if (next == null)

View File

@ -2,9 +2,11 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
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
{
/// <summary>
/// Configuration options for <see cref="OAuthMiddleware"/>.

View File

@ -2,8 +2,8 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Microsoft.AspNet.Authentication.OpenIdConnect
{

View File

@ -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;

View File

@ -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;

View File

@ -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
{

View File

@ -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;

View File

@ -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
{

View File

@ -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
{

View File

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

View File

@ -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

View File

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

View File

@ -13,6 +13,7 @@ using System.Security.Cryptography;
using System.Text;
using System.Text.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;

View File

@ -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<SharedAuthenticationOptions> sharedOptions,
OpenIdConnectOptions options,
IOptions<OpenIdConnectOptions> options,
HtmlEncoder htmlEncoder)
: base(next, options, loggerFactory, encoder)
{

View File

@ -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
{
/// <summary>
/// Configuration options for <see cref="OpenIdConnectOptions"/>

View File

@ -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

View File

@ -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;

View File

@ -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;

View File

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

View File

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

View File

@ -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<SharedAuthenticationOptions> sharedOptions,
TwitterOptions options)
IOptions<TwitterOptions> options)
: base(next, options, loggerFactory, encoder)
{
if (next == null)

View File

@ -2,10 +2,11 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
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
{
/// <summary>
/// Options for the Twitter authentication middleware.

View File

@ -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;

View File

@ -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<TOptions> 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;

View File

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

View File

@ -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
/// </summary>
public static class ClaimsTransformationAppBuilderExtensions
{
/// <summary>
/// Adds the <see cref="ClaimsTransformationMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables claims transformation capabilities.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseClaimsTransformation(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseMiddleware<ClaimsTransformationMiddleware>();
}
/// <summary>
/// Adds the <see cref="ClaimsTransformationMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables claims transformation capabilities.
/// </summary>
@ -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 }
});
}
/// <summary>
/// Adds the <see cref="ClaimsTransformationMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables claims transformation capabilities.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
/// <param name="configureOptions">An action delegate to configure the provided <see cref="ClaimsTransformationOptions"/>.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
public static IApplicationBuilder UseClaimsTransformation(this IApplicationBuilder app, Action<ClaimsTransformationOptions> configureOptions)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var options = new ClaimsTransformationOptions();
configureOptions(options);
return app.UseMiddleware<ClaimsTransformationMiddleware>(options);
}
/// <summary>
/// Adds the <see cref="ClaimsTransformationMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables claims transformation capabilities.
/// </summary>
@ -76,7 +69,7 @@ namespace Microsoft.AspNet.Builder
throw new ArgumentNullException(nameof(options));
}
return app.UseMiddleware<ClaimsTransformationMiddleware>(options);
return app.UseMiddleware<ClaimsTransformationMiddleware>(Options.Create(options));
}
}
}

View File

@ -3,7 +3,9 @@
using System;
using System.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<ClaimsTransformationOptions> options)
{
if (next == null)
{
@ -25,7 +27,7 @@ namespace Microsoft.AspNet.Authentication
throw new ArgumentNullException(nameof(options));
}
Options = options;
Options = options.Value;
_next = next;
}

View File

@ -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
{

View File

@ -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;

View File

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

View File

@ -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
{

View File

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

View File

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

View File

@ -3,9 +3,10 @@
using System;
using System.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<CookiePolicyOptions> options)
{
Options = options;
Options = options.Value;
_next = next;
}

View File

@ -2,8 +2,9 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.CookiePolicy;
namespace Microsoft.AspNet.CookiePolicy
namespace Microsoft.AspNet.Builder
{
public class CookiePolicyOptions
{

View File

@ -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": {},

View File

@ -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;

View File

@ -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<InvalidOperationException>(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<InvalidOperationException>(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<CookieAuthenticationOptions> configureOptions, Func<HttpContext, Task> testpath = null, Uri baseAddress = null, Action<ClaimsTransformationOptions> claimsTransform = null)
private static TestServer CreateServer(CookieAuthenticationOptions options, Func<HttpContext, Task> testpath = null, Uri baseAddress = null, ClaimsTransformationOptions claimsTransform = null)
{
var builder = new WebApplicationBuilder()
.Configure(app =>
{
app.UseCookieAuthentication(configureOptions);
app.UseCookieAuthentication(options);
// app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie2" });
if (claimsTransform != null)

View File

@ -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 =>

View File

@ -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<Exception>(() => 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<GoogleOptions> configureOptions, Func<HttpContext, Task> testpath = null)
private static TestServer CreateServer(GoogleOptions options, Func<HttpContext, Task> 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);
}

View File

@ -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<object>(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<object>(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<object>(null);
}
};
options.SecurityTokenValidators.Add(new BlobTokenValidator(options.AuthenticationScheme));
});
}
};
options.SecurityTokenValidators.Add(new BlobTokenValidator(options.AuthenticationScheme));
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
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<object>(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<object>(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<object>(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<JwtBearerOptions> configureOptions, Func<HttpContext, bool> handler = null)
private static TestServer CreateServer(JwtBearerOptions options, Func<HttpContext, bool> 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) =>

View File

@ -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<object>(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<MicrosoftAccountOptions> 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<SharedAuthenticationOptions>(options =>
services.Configure<SharedAuthenticationOptions>(authOptions =>
{
options.SignInScheme = TestExtensions.CookieAuthenticationScheme;
authOptions.SignInScheme = TestExtensions.CookieAuthenticationScheme;
});
});
return new TestServer(builder);

View File

@ -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<OpenIdConnectOptions> 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<Action<OpenIdConnectOptions>, OpenIdConnectMessage> AuthenticateCoreStateDataSet
public static TheoryData<OpenIdConnectOptions, OpenIdConnectMessage> AuthenticateCoreStateDataSet
{
get
{
var formater = new AuthenticationPropertiesFormaterKeyValue();
var properties = new AuthenticationProperties();
var dataset = new TheoryData<Action<OpenIdConnectOptions>, OpenIdConnectMessage>();
var dataset = new TheoryData<OpenIdConnectOptions, OpenIdConnectMessage>();
// expected user state is added to the message.Parameters.Items[ExpectedStateParameter]
// 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<object>(null);
}
};
return options;
}
private static TestServer CreateServer(Action<OpenIdConnectOptions> configureOptions, UrlEncoder encoder, OpenIdConnectHandler handler = null)
private static TestServer CreateServer(OpenIdConnectOptions options, UrlEncoder encoder, OpenIdConnectHandler handler = null)
{
var builder = new WebApplicationBuilder()
.Configure(app =>
{
var options = new OpenIdConnectOptions();
configureOptions(options);
app.UseMiddleware<OpenIdConnectMiddlewareForTestingAuthenticate>(options, encoder, handler);
app.UseMiddleware<OpenIdConnectMiddlewareForTestingAuthenticate>(Options.Create(options), encoder, handler);
app.Use(async (context, next) =>
{
await next();

View File

@ -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<SharedAuthenticationOptions> sharedOptions,
OpenIdConnectOptions options,
IOptions<OpenIdConnectOptions> options,
HtmlEncoder htmlEncoder,
OpenIdConnectHandler handler = null
)

View File

@ -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<object>(null);
}
context.ProtocolMessage.State = userState;
context.ProtocolMessage.RedirectUri = queryValues.RedirectUri;
return Task.FromResult<object>(null);
}
};
}, null, properties);
};
var server = CreateServer(options, null, properties);
var transaction = await SendAsync(server, DefaultHost + challenge);
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<object>(null);
}
};
});
context.ProtocolMessage.ClientId = queryValuesSetInEvent.ClientId;
context.ProtocolMessage.RedirectUri = queryValuesSetInEvent.RedirectUri;
context.ProtocolMessage.Resource = queryValuesSetInEvent.Resource;
context.ProtocolMessage.Scope = queryValuesSetInEvent.Scope;
return Task.FromResult<object>(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<string> parameters, ExpectedQueryValues queryValues, ISecureDataFormat<AuthenticationProperties> secureDataFormat = null)
private OpenIdConnectOptions GetOptions(List<string> parameters, ExpectedQueryValues queryValues, ISecureDataFormat<AuthenticationProperties> secureDataFormat = null)
{
var options = new OpenIdConnectOptions();
foreach (var param in parameters)
{
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<string> 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<OpenIdConnectOptions> configureOptions, Func<HttpContext, Task> handler = null, AuthenticationProperties properties = null)
private static TestServer CreateServer(OpenIdConnectOptions options, Func<HttpContext, Task> handler = null, AuthenticationProperties properties = null)
{
var builder = new WebApplicationBuilder()
.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<SharedAuthenticationOptions>(options =>
services.Configure<SharedAuthenticationOptions>(authOptions =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
authOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
});
return new TestServer(builder);

View File

@ -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<TwitterOptions> configure, Func<HttpContext, bool> handler = null)
private static TestServer CreateServer(TwitterOptions options, Func<HttpContext, bool> 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<SharedAuthenticationOptions>(options =>
services.Configure<SharedAuthenticationOptions>(authOptions =>
{
options.SignInScheme = "External";
authOptions.SignInScheme = "External";
});
});
return new TestServer(builder);

View File

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

View File

@ -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<IResponseCookiesFeature>(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<NotImplementedException>(() => context.Response.Cookies.Delete("A"));
@ -254,7 +278,7 @@ namespace Microsoft.AspNet.CookiePolicy.Test
private async Task RunTest(
string path,
Action<CookiePolicyOptions> 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);
});
});

View File

@ -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))
});