Skip to content
This repository was archived by the owner on Dec 13, 2018. It is now read-only.

Commit 1f5a27e

Browse files
committed
Switch to Options Initializer
1 parent bdd4d21 commit 1f5a27e

File tree

35 files changed

+434
-325
lines changed

35 files changed

+434
-325
lines changed

samples/SocialSample/Startup.cs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@ public void ConfigureServices(IServiceCollection services)
7575
// https://console.developers.google.com/project
7676
services.AddOAuthAuthentication("Google-AccessToken", o =>
7777
{
78-
o.DisplayName = "Google-AccessToken";
7978
o.ClientId = Configuration["google:clientid"];
8079
o.ClientSecret = Configuration["google:clientsecret"];
8180
o.CallbackPath = new PathString("/signin-google-token");
@@ -137,7 +136,6 @@ public void ConfigureServices(IServiceCollection services)
137136
// https://apps.dev.microsoft.com/
138137
services.AddOAuthAuthentication("Microsoft-AccessToken", o =>
139138
{
140-
o.DisplayName = "MicrosoftAccount-AccessToken";
141139
o.ClientId = Configuration["microsoftaccount:clientid"];
142140
o.ClientSecret = Configuration["microsoftaccount:clientsecret"];
143141
o.CallbackPath = new PathString("/signin-microsoft-token");
@@ -160,7 +158,6 @@ public void ConfigureServices(IServiceCollection services)
160158
// https://github.com/settings/applications/
161159
services.AddOAuthAuthentication("GitHub-AccessToken", o =>
162160
{
163-
o.DisplayName = "Github-AccessToken";
164161
o.ClientId = Configuration["github-token:clientid"];
165162
o.ClientSecret = Configuration["github-token:clientsecret"];
166163
o.CallbackPath = new PathString("/signin-github-token");
@@ -178,7 +175,6 @@ public void ConfigureServices(IServiceCollection services)
178175
// https://github.com/settings/applications/
179176
services.AddOAuthAuthentication("GitHub", o =>
180177
{
181-
o.DisplayName = "Github";
182178
o.ClientId = Configuration["github:clientid"];
183179
o.ClientSecret = Configuration["github:clientsecret"];
184180
o.CallbackPath = new PathString("/signin-github");

src/Microsoft.AspNetCore.Authentication.Cookies/CookieAuthenticationHandler.cs

Lines changed: 0 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -59,39 +59,6 @@ protected override Task InitializeHandlerAsync()
5959
/// <returns>A new instance of the events instance.</returns>
6060
protected override Task<object> CreateEventsAsync() => Task.FromResult<object>(new CookieAuthenticationEvents());
6161

62-
protected override void InitializeOptions()
63-
{
64-
base.InitializeOptions();
65-
66-
if (String.IsNullOrEmpty(Options.CookieName))
67-
{
68-
Options.CookieName = CookieAuthenticationDefaults.CookiePrefix + Scheme.Name;
69-
}
70-
if (Options.TicketDataFormat == null)
71-
{
72-
var provider = Options.DataProtectionProvider ?? Context.RequestServices.GetRequiredService<IDataProtectionProvider>();
73-
// Note: the purpose for the data protector must remain fixed for interop to work.
74-
var dataProtector = provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", Scheme.Name, "v2");
75-
Options.TicketDataFormat = new TicketDataFormat(dataProtector);
76-
}
77-
if (Options.CookieManager == null)
78-
{
79-
Options.CookieManager = new ChunkingCookieManager();
80-
}
81-
if (!Options.LoginPath.HasValue)
82-
{
83-
Options.LoginPath = CookieAuthenticationDefaults.LoginPath;
84-
}
85-
if (!Options.LogoutPath.HasValue)
86-
{
87-
Options.LogoutPath = CookieAuthenticationDefaults.LogoutPath;
88-
}
89-
if (!Options.AccessDeniedPath.HasValue)
90-
{
91-
Options.AccessDeniedPath = CookieAuthenticationDefaults.AccessDeniedPath;
92-
}
93-
}
94-
9562
private Task<AuthenticateResult> EnsureCookieTicket()
9663
{
9764
// We only need to read the ticket once
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
using System;
5+
using Microsoft.AspNetCore.DataProtection;
6+
using Microsoft.Extensions.Options;
7+
8+
namespace Microsoft.AspNetCore.Authentication.Cookies
9+
{
10+
/// <summary>
11+
/// Used to setup defaults for all <see cref="CookieAuthenticationOptions"/>.
12+
/// </summary>
13+
public class CookieAuthenticationInitializer : IInitializeOptions<CookieAuthenticationOptions>
14+
{
15+
private readonly IDataProtectionProvider _dp;
16+
17+
public CookieAuthenticationInitializer(IDataProtectionProvider dataProtection)
18+
{
19+
_dp = dataProtection;
20+
}
21+
22+
/// <summary>
23+
/// Invoked to initialize a TOptions instance.
24+
/// </summary>
25+
/// <param name="name">The name of the options instance being initialized.</param>
26+
/// <param name="options">The options instance to initialize.</param>
27+
public void Initialize(string name, CookieAuthenticationOptions options)
28+
{
29+
options.DataProtectionProvider = options.DataProtectionProvider ?? _dp;
30+
31+
if (String.IsNullOrEmpty(options.CookieName))
32+
{
33+
options.CookieName = CookieAuthenticationDefaults.CookiePrefix + name;
34+
}
35+
if (options.TicketDataFormat == null)
36+
{
37+
// Note: the purpose for the data protector must remain fixed for interop to work.
38+
var dataProtector = options.DataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", name, "v2");
39+
options.TicketDataFormat = new TicketDataFormat(dataProtector);
40+
}
41+
if (options.CookieManager == null)
42+
{
43+
options.CookieManager = new ChunkingCookieManager();
44+
}
45+
if (!options.LoginPath.HasValue)
46+
{
47+
options.LoginPath = CookieAuthenticationDefaults.LoginPath;
48+
}
49+
if (!options.LogoutPath.HasValue)
50+
{
51+
options.LogoutPath = CookieAuthenticationDefaults.LogoutPath;
52+
}
53+
if (!options.AccessDeniedPath.HasValue)
54+
{
55+
options.AccessDeniedPath = CookieAuthenticationDefaults.AccessDeniedPath;
56+
}
57+
}
58+
59+
}
60+
}

src/Microsoft.AspNetCore.Authentication.Cookies/CookieAuthenticationOptions.cs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System;
55
using Microsoft.AspNetCore.DataProtection;
66
using Microsoft.AspNetCore.Http;
7+
using Microsoft.Extensions.Options;
78

89
namespace Microsoft.AspNetCore.Authentication.Cookies
910
{
@@ -71,7 +72,7 @@ public string CookieName
7172
public CookieSecurePolicy CookieSecure { get; set; }
7273

7374
/// <summary>
74-
/// If set this will be used by the CookieAuthenticationMiddleware for data protection.
75+
/// If set this will be used by the CookieAuthenticationHandler for data protection.
7576
/// </summary>
7677
public IDataProtectionProvider DataProtectionProvider { get; set; }
7778

@@ -129,9 +130,7 @@ public string CookieName
129130

130131
/// <summary>
131132
/// The TicketDataFormat is used to protect and unprotect the identity and other properties which are stored in the
132-
/// cookie value. If it is not provided a default data handler is created using the data protection service contained
133-
/// in the IApplicationBuilder.Properties. The default data protection service is based on machine key when running on ASP.NET,
134-
/// and on DPAPI when running in a different process.
133+
/// cookie value. If not provided one will be created using <see cref="DataProtectionProvider"/>.
135134
/// </summary>
136135
public ISecureDataFormat<AuthenticationTicket> TicketDataFormat { get; set; }
137136

src/Microsoft.AspNetCore.Authentication.Cookies/CookieExtensions.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33

44
using System;
55
using Microsoft.AspNetCore.Authentication.Cookies;
6+
using Microsoft.AspNetCore.DataProtection;
7+
using Microsoft.Extensions.Options;
8+
using Microsoft.Extensions.DependencyInjection.Extensions;
9+
using Microsoft.AspNetCore.Authentication;
610

711
namespace Microsoft.Extensions.DependencyInjection
812
{
@@ -15,7 +19,10 @@ public static class CookieExtensions
1519
public static IServiceCollection AddCookieAuthentication(this IServiceCollection services, Action<CookieAuthenticationOptions> configureOptions) =>
1620
services.AddCookieAuthentication(CookieAuthenticationDefaults.AuthenticationScheme, configureOptions);
1721

18-
public static IServiceCollection AddCookieAuthentication(this IServiceCollection services, string authenticationScheme, Action<CookieAuthenticationOptions> configureOptions) =>
19-
services.AddScheme<CookieAuthenticationOptions, CookieAuthenticationHandler>(authenticationScheme, configureOptions);
22+
public static IServiceCollection AddCookieAuthentication(this IServiceCollection services, string authenticationScheme, Action<CookieAuthenticationOptions> configureOptions)
23+
{
24+
services.TryAddEnumerable(ServiceDescriptor.Singleton<IInitializeOptions<CookieAuthenticationOptions>, CookieAuthenticationInitializer>());
25+
return services.AddScheme<CookieAuthenticationOptions, CookieAuthenticationHandler>(authenticationScheme, configureOptions);
26+
}
2027
}
2128
}

src/Microsoft.AspNetCore.Authentication.Facebook/FacebookExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public static IServiceCollection AddFacebookAuthentication(this IServiceCollecti
2626

2727
public static IServiceCollection AddFacebookAuthentication(this IServiceCollection services, string authenticationScheme, Action<FacebookOptions> configureOptions)
2828
{
29-
return services.AddScheme<FacebookOptions, FacebookHandler>(authenticationScheme, authenticationScheme, configureOptions);
29+
return services.AddOAuthAuthentication<FacebookOptions, FacebookHandler>(authenticationScheme, configureOptions);
3030
}
3131
}
3232
}

src/Microsoft.AspNetCore.Authentication.Facebook/FacebookHandler.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
using System.Text.Encodings.Web;
1010
using System.Threading.Tasks;
1111
using Microsoft.AspNetCore.Authentication.OAuth;
12-
using Microsoft.AspNetCore.DataProtection;
1312
using Microsoft.AspNetCore.WebUtilities;
1413
using Microsoft.Extensions.Logging;
1514
using Microsoft.Extensions.Options;
@@ -19,8 +18,8 @@ namespace Microsoft.AspNetCore.Authentication.Facebook
1918
{
2019
internal class FacebookHandler : OAuthHandler<FacebookOptions>
2120
{
22-
public FacebookHandler(IOptions<AuthenticationOptions> sharedOptions, IOptionsSnapshot<FacebookOptions> options, ILoggerFactory logger, UrlEncoder encoder, IDataProtectionProvider dataProtection, ISystemClock clock)
23-
: base(sharedOptions, options, logger, encoder, dataProtection, clock)
21+
public FacebookHandler(IOptionsSnapshot<FacebookOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
22+
: base(options, logger, encoder, clock)
2423
{ }
2524

2625
protected override async Task<AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens)

src/Microsoft.AspNetCore.Authentication.Google/GoogleExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public static IServiceCollection AddGoogleAuthentication(this IServiceCollection
2626

2727
public static IServiceCollection AddGoogleAuthentication(this IServiceCollection services, string authenticationScheme, Action<GoogleOptions> configureOptions)
2828
{
29-
return services.AddScheme<GoogleOptions, GoogleHandler>(authenticationScheme, authenticationScheme, configureOptions);
29+
return services.AddOAuthAuthentication<GoogleOptions, GoogleHandler>(authenticationScheme, configureOptions);
3030
}
3131
}
3232
}

src/Microsoft.AspNetCore.Authentication.Google/GoogleHandler.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
using System.Text.Encodings.Web;
1010
using System.Threading.Tasks;
1111
using Microsoft.AspNetCore.Authentication.OAuth;
12-
using Microsoft.AspNetCore.DataProtection;
1312
using Microsoft.AspNetCore.WebUtilities;
1413
using Microsoft.Extensions.Logging;
1514
using Microsoft.Extensions.Options;
@@ -19,8 +18,8 @@ namespace Microsoft.AspNetCore.Authentication.Google
1918
{
2019
internal class GoogleHandler : OAuthHandler<GoogleOptions>
2120
{
22-
public GoogleHandler(IOptions<AuthenticationOptions> sharedOptions, IOptionsSnapshot<GoogleOptions> options, ILoggerFactory logger, UrlEncoder encoder, IDataProtectionProvider dataProtection, ISystemClock clock)
23-
: base(sharedOptions, options, logger, encoder, dataProtection, clock)
21+
public GoogleHandler(IOptionsSnapshot<GoogleOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
22+
: base(options, logger, encoder, clock)
2423
{ }
2524

2625
protected override async Task<AuthenticationTicket> CreateTicketAsync(

src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerExtensions.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using System;
55
using Microsoft.AspNetCore.Authentication.JwtBearer;
6+
using Microsoft.Extensions.DependencyInjection.Extensions;
67
using Microsoft.Extensions.Options;
78

89
namespace Microsoft.Extensions.DependencyInjection
@@ -26,6 +27,7 @@ public static IServiceCollection AddJwtBearerAuthentication(this IServiceCollect
2627

2728
public static IServiceCollection AddJwtBearerAuthentication(this IServiceCollection services, string authenticationScheme, Action<JwtBearerOptions> configureOptions)
2829
{
30+
services.TryAddEnumerable(ServiceDescriptor.Singleton<IInitializeOptions<JwtBearerOptions>, JwtBearerInitializer>());
2931
return services.AddScheme<JwtBearerOptions, JwtBearerHandler>(authenticationScheme, configureOptions);
3032
}
3133
}

src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerHandler.cs

Lines changed: 0 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -40,49 +40,6 @@ public JwtBearerHandler(IOptionsSnapshot<JwtBearerOptions> options, ILoggerFacto
4040

4141
protected override Task<object> CreateEventsAsync() => Task.FromResult<object>(new JwtBearerEvents());
4242

43-
protected override void InitializeOptions()
44-
{
45-
base.InitializeOptions();
46-
47-
if (string.IsNullOrEmpty(Options.TokenValidationParameters.ValidAudience) && !string.IsNullOrEmpty(Options.Audience))
48-
{
49-
Options.TokenValidationParameters.ValidAudience = Options.Audience;
50-
}
51-
52-
if (Options.ConfigurationManager == null)
53-
{
54-
if (Options.Configuration != null)
55-
{
56-
Options.ConfigurationManager = new StaticConfigurationManager<OpenIdConnectConfiguration>(Options.Configuration);
57-
}
58-
else if (!(string.IsNullOrEmpty(Options.MetadataAddress) && string.IsNullOrEmpty(Options.Authority)))
59-
{
60-
if (string.IsNullOrEmpty(Options.MetadataAddress) && !string.IsNullOrEmpty(Options.Authority))
61-
{
62-
Options.MetadataAddress = Options.Authority;
63-
if (!Options.MetadataAddress.EndsWith("/", StringComparison.Ordinal))
64-
{
65-
Options.MetadataAddress += "/";
66-
}
67-
68-
Options.MetadataAddress += ".well-known/openid-configuration";
69-
}
70-
71-
if (Options.RequireHttpsMetadata && !Options.MetadataAddress.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
72-
{
73-
throw new InvalidOperationException("The MetadataAddress or Authority must use HTTPS unless disabled for development by setting RequireHttpsMetadata=false.");
74-
}
75-
76-
var httpClient = new HttpClient(Options.BackchannelHttpHandler ?? new HttpClientHandler());
77-
httpClient.Timeout = Options.BackchannelTimeout;
78-
httpClient.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
79-
80-
Options.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(Options.MetadataAddress, new OpenIdConnectConfigurationRetriever(),
81-
new HttpDocumentRetriever(httpClient) { RequireHttps = Options.RequireHttpsMetadata });
82-
}
83-
}
84-
}
85-
8643
/// <summary>
8744
/// Searches the 'Authorization' header for a 'Bearer' token. If the 'Bearer' token is found, it is validated using <see cref="TokenValidationParameters"/> set in the options.
8845
/// </summary>
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
using System;
5+
using System.Net.Http;
6+
using Microsoft.Extensions.Options;
7+
using Microsoft.IdentityModel.Protocols;
8+
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
9+
10+
namespace Microsoft.AspNetCore.Authentication.JwtBearer
11+
{
12+
/// <summary>
13+
/// Used to setup defaults for all <see cref="JwtBearerOptions"/>.
14+
/// </summary>
15+
public class JwtBearerInitializer : IInitializeOptions<JwtBearerOptions>
16+
{
17+
/// <summary>
18+
/// Invoked to initialize a JwtBearerOptions instance.
19+
/// </summary>
20+
/// <param name="name">The name of the options instance being initialized.</param>
21+
/// <param name="options">The options instance to initialize.</param>
22+
public void Initialize(string name, JwtBearerOptions options)
23+
{
24+
if (string.IsNullOrEmpty(options.TokenValidationParameters.ValidAudience) && !string.IsNullOrEmpty(options.Audience))
25+
{
26+
options.TokenValidationParameters.ValidAudience = options.Audience;
27+
}
28+
29+
if (options.ConfigurationManager == null)
30+
{
31+
if (options.Configuration != null)
32+
{
33+
options.ConfigurationManager = new StaticConfigurationManager<OpenIdConnectConfiguration>(options.Configuration);
34+
}
35+
else if (!(string.IsNullOrEmpty(options.MetadataAddress) && string.IsNullOrEmpty(options.Authority)))
36+
{
37+
if (string.IsNullOrEmpty(options.MetadataAddress) && !string.IsNullOrEmpty(options.Authority))
38+
{
39+
options.MetadataAddress = options.Authority;
40+
if (!options.MetadataAddress.EndsWith("/", StringComparison.Ordinal))
41+
{
42+
options.MetadataAddress += "/";
43+
}
44+
45+
options.MetadataAddress += ".well-known/openid-configuration";
46+
}
47+
48+
if (options.RequireHttpsMetadata && !options.MetadataAddress.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
49+
{
50+
throw new InvalidOperationException("The MetadataAddress or Authority must use HTTPS unless disabled for development by setting RequireHttpsMetadata=false.");
51+
}
52+
53+
var httpClient = new HttpClient(options.BackchannelHttpHandler ?? new HttpClientHandler());
54+
httpClient.Timeout = options.BackchannelTimeout;
55+
httpClient.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
56+
57+
options.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(options.MetadataAddress, new OpenIdConnectConfigurationRetriever(),
58+
new HttpDocumentRetriever(httpClient) { RequireHttps = options.RequireHttpsMetadata });
59+
}
60+
}
61+
}
62+
}
63+
}

src/Microsoft.AspNetCore.Authentication.MicrosoftAccount/MicrosoftAccountExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public static IServiceCollection AddMicrosoftAccountAuthentication(this IService
2626

2727
public static IServiceCollection AddMicrosoftAccountAuthentication(this IServiceCollection services, string authenticationScheme, Action<MicrosoftAccountOptions> configureOptions)
2828
{
29-
return services.AddScheme<MicrosoftAccountOptions, MicrosoftAccountHandler>(authenticationScheme, authenticationScheme, configureOptions);
29+
return services.AddOAuthAuthentication<MicrosoftAccountOptions, MicrosoftAccountHandler>(authenticationScheme, configureOptions);
3030
}
3131
}
3232
}

0 commit comments

Comments
 (0)