-
Notifications
You must be signed in to change notification settings - Fork 219
/
Copy pathWebAppAuthenticationBuilderExtensions.cs
264 lines (234 loc) · 15.2 KB
/
WebAppAuthenticationBuilderExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OAuth.Claims;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Microsoft.Identity.Web.Resource;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Microsoft.Identity.Web
{
/// <summary>
/// Extensions for the <see cref="AuthenticationBuilder"/> for startup initialization.
/// </summary>
public static partial class WebAppAuthenticationBuilderExtensions
{
/// <summary>
/// Add authentication with Microsoft identity platform.
/// This method expects the configuration file will have a section, named "AzureAd" as default, with the necessary settings to initialize authentication options.
/// </summary>
/// <param name="builder">The <see cref="AuthenticationBuilder"/> to which to add this configuration.</param>
/// <param name="configuration">The configuration instance.</param>
/// <param name="configSectionName">The configuration section with the necessary settings to initialize authentication options.</param>
/// <param name="openIdConnectScheme">The OpenID Connect scheme name to be used. By default it uses "OpenIdConnect".</param>
/// <param name="cookieScheme">The cookie-based scheme name to be used. By default it uses "Cookies".</param>
/// <param name="subscribeToOpenIdConnectMiddlewareDiagnosticsEvents">
/// Set to true if you want to debug, or just understand the OpenID Connect events.
/// </param>
/// <returns>The authentication builder for chaining.</returns>
public static AuthenticationBuilder AddMicrosoftWebApp(
this AuthenticationBuilder builder,
IConfiguration configuration,
string configSectionName = Constants.AzureAd,
string openIdConnectScheme = OpenIdConnectDefaults.AuthenticationScheme,
string cookieScheme = CookieAuthenticationDefaults.AuthenticationScheme,
bool subscribeToOpenIdConnectMiddlewareDiagnosticsEvents = false) =>
builder.AddMicrosoftWebApp(
options => configuration.Bind(configSectionName, options),
null,
openIdConnectScheme,
cookieScheme,
subscribeToOpenIdConnectMiddlewareDiagnosticsEvents);
/// <summary>
/// Add authentication with Microsoft identity platform.
/// </summary>
/// <param name="builder">The <see cref="AuthenticationBuilder"/> to which to add this configuration.</param>
/// <param name="configureMicrosoftIdentityOptions">The action to configure <see cref="MicrosoftIdentityOptions"/>.</param>
/// <param name="configureCookieAuthenticationOptions">The action to configure <see cref="CookieAuthenticationOptions"/>.</param>
/// <param name="openIdConnectScheme">The OpenID Connect scheme name to be used. By default it uses "OpenIdConnect".</param>
/// <param name="cookieScheme">The cookie-based scheme name to be used. By default it uses "Cookies".</param>
/// <param name="subscribeToOpenIdConnectMiddlewareDiagnosticsEvents">
/// Set to true if you want to debug, or just understand the OpenID Connect events.
/// </param>
/// <returns>The authentication builder for chaining.</returns>
public static AuthenticationBuilder AddMicrosoftWebApp(
this AuthenticationBuilder builder,
Action<MicrosoftIdentityOptions> configureMicrosoftIdentityOptions,
Action<CookieAuthenticationOptions>? configureCookieAuthenticationOptions = null,
string openIdConnectScheme = OpenIdConnectDefaults.AuthenticationScheme,
string cookieScheme = CookieAuthenticationDefaults.AuthenticationScheme,
bool subscribeToOpenIdConnectMiddlewareDiagnosticsEvents = false)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (configureMicrosoftIdentityOptions == null)
{
throw new ArgumentNullException(nameof(configureMicrosoftIdentityOptions));
}
builder.Services.Configure(configureMicrosoftIdentityOptions);
builder.Services.AddHttpClient();
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IValidateOptions<MicrosoftIdentityOptions>, MicrosoftIdentityOptionsValidation>());
builder.AddCookie(cookieScheme, configureCookieAuthenticationOptions);
if (subscribeToOpenIdConnectMiddlewareDiagnosticsEvents)
{
builder.Services.AddSingleton<IOpenIdConnectMiddlewareDiagnostics, OpenIdConnectMiddlewareDiagnostics>();
}
builder.AddOpenIdConnect(openIdConnectScheme, options => { });
builder.Services.AddOptions<OpenIdConnectOptions>(openIdConnectScheme)
.Configure<IServiceProvider, IOptions<MicrosoftIdentityOptions>>((options, serviceProvider, microsoftIdentityOptions) =>
{
PopulateOpenIdOptionsFromMicrosoftIdentityOptions(options, microsoftIdentityOptions.Value);
var b2cOidcHandlers = new AzureADB2COpenIDConnectEventHandlers(openIdConnectScheme, microsoftIdentityOptions.Value);
options.SignInScheme = cookieScheme;
if (string.IsNullOrWhiteSpace(options.Authority))
{
options.Authority = AuthorityHelpers.BuildAuthority(microsoftIdentityOptions.Value);
}
// This is a Microsoft identity platform Web app
options.Authority = AuthorityHelpers.EnsureAuthorityIsV2(options.Authority);
options.TokenValidationParameters = options.TokenValidationParameters.Clone();
// B2C doesn't have preferred_username claims
if (microsoftIdentityOptions.Value.IsB2C)
{
options.TokenValidationParameters.NameClaimType = Constants.NameClaim;
}
else
{
options.TokenValidationParameters.NameClaimType = Constants.PreferredUserName;
}
// If the developer registered an IssuerValidator, do not overwrite it
if (options.TokenValidationParameters.IssuerValidator == null)
{
// If you want to restrict the users that can sign-in to several organizations
// Set the tenant value in the appsettings.json file to 'organizations', and add the
// issuers you want to accept to options.TokenValidationParameters.ValidIssuers collection
options.TokenValidationParameters.IssuerValidator = AadIssuerValidator.GetIssuerValidator(options.Authority).Validate;
}
// Avoids having users being presented the select account dialog when they are already signed-in
// for instance when going through incremental consent
var redirectToIdpHandler = options.Events.OnRedirectToIdentityProvider;
options.Events.OnRedirectToIdentityProvider = async context =>
{
var login = context.Properties.GetParameter<string>(OpenIdConnectParameterNames.LoginHint);
if (!string.IsNullOrWhiteSpace(login))
{
context.ProtocolMessage.LoginHint = login;
context.ProtocolMessage.DomainHint = context.Properties.GetParameter<string>(
OpenIdConnectParameterNames.DomainHint);
// delete the login_hint and domainHint from the Properties when we are done otherwise
// it will take up extra space in the cookie.
context.Properties.Parameters.Remove(OpenIdConnectParameterNames.LoginHint);
context.Properties.Parameters.Remove(OpenIdConnectParameterNames.DomainHint);
}
context.ProtocolMessage.SetParameter(Constants.ClientInfo, Constants.One);
// Additional claims
if (context.Properties.Items.ContainsKey(OidcConstants.AdditionalClaims))
{
context.ProtocolMessage.SetParameter(
OidcConstants.AdditionalClaims,
context.Properties.Items[OidcConstants.AdditionalClaims]);
}
if (microsoftIdentityOptions.Value.IsB2C)
{
// When a new Challenge is returned using any B2C user flow different than susi, we must change
// the ProtocolMessage.IssuerAddress to the desired user flow otherwise the redirect would use the susi user flow
await b2cOidcHandlers.OnRedirectToIdentityProvider(context).ConfigureAwait(false);
}
await redirectToIdpHandler(context).ConfigureAwait(false);
};
if (microsoftIdentityOptions.Value.IsB2C)
{
var remoteFailureHandler = options.Events.OnRemoteFailure;
options.Events.OnRemoteFailure = async context =>
{
// Handles the error when a user cancels an action on the Azure Active Directory B2C UI.
// Handle the error code that Azure Active Directory B2C throws when trying to reset a password from the login page
// because password reset is not supported by a "sign-up or sign-in user flow".
await b2cOidcHandlers.OnRemoteFailure(context).ConfigureAwait(false);
await remoteFailureHandler(context).ConfigureAwait(false);
};
}
if (subscribeToOpenIdConnectMiddlewareDiagnosticsEvents)
{
var diagnostics = serviceProvider.GetRequiredService<IOpenIdConnectMiddlewareDiagnostics>();
diagnostics.Subscribe(options.Events);
}
});
return builder;
}
internal static void PopulateOpenIdOptionsFromMicrosoftIdentityOptions(OpenIdConnectOptions options, MicrosoftIdentityOptions microsoftIdentityOptions)
{
options.Authority = microsoftIdentityOptions.Authority;
options.ClientId = microsoftIdentityOptions.ClientId;
options.ClientSecret = microsoftIdentityOptions.ClientSecret;
options.Configuration = microsoftIdentityOptions.Configuration;
options.ConfigurationManager = microsoftIdentityOptions.ConfigurationManager;
options.GetClaimsFromUserInfoEndpoint = microsoftIdentityOptions.GetClaimsFromUserInfoEndpoint;
foreach (ClaimAction c in microsoftIdentityOptions.ClaimActions)
{
options.ClaimActions.Add(c);
}
options.RequireHttpsMetadata = microsoftIdentityOptions.RequireHttpsMetadata;
options.MetadataAddress = microsoftIdentityOptions.MetadataAddress;
options.Events = microsoftIdentityOptions.Events;
options.MaxAge = microsoftIdentityOptions.MaxAge;
options.ProtocolValidator = microsoftIdentityOptions.ProtocolValidator;
options.SignedOutCallbackPath = microsoftIdentityOptions.SignedOutCallbackPath;
options.SignedOutRedirectUri = microsoftIdentityOptions.SignedOutRedirectUri;
options.RefreshOnIssuerKeyNotFound = microsoftIdentityOptions.RefreshOnIssuerKeyNotFound;
options.AuthenticationMethod = microsoftIdentityOptions.AuthenticationMethod;
options.Resource = microsoftIdentityOptions.Resource;
options.ResponseMode = microsoftIdentityOptions.ResponseMode;
options.ResponseType = microsoftIdentityOptions.ResponseType;
options.Prompt = microsoftIdentityOptions.Prompt;
foreach (string scope in microsoftIdentityOptions.Scope)
{
options.Scope.Add(scope);
}
options.RemoteSignOutPath = microsoftIdentityOptions.RemoteSignOutPath;
options.SignOutScheme = microsoftIdentityOptions.SignOutScheme;
options.StateDataFormat = microsoftIdentityOptions.StateDataFormat;
options.StringDataFormat = microsoftIdentityOptions.StringDataFormat;
options.SecurityTokenValidator = microsoftIdentityOptions.SecurityTokenValidator;
options.TokenValidationParameters = microsoftIdentityOptions.TokenValidationParameters;
options.UseTokenLifetime = microsoftIdentityOptions.UseTokenLifetime;
options.SkipUnrecognizedRequests = microsoftIdentityOptions.SkipUnrecognizedRequests;
options.DisableTelemetry = microsoftIdentityOptions.DisableTelemetry;
options.NonceCookie = microsoftIdentityOptions.NonceCookie;
options.UsePkce = microsoftIdentityOptions.UsePkce;
#if DOTNET_50_AND_ABOVE
options.AutomaticRefreshInterval = microsoftIdentityOptions.AutomaticRefreshInterval;
options.RefreshInterval = microsoftIdentityOptions.RefreshInterval;
#endif
options.BackchannelTimeout = microsoftIdentityOptions.BackchannelTimeout;
options.BackchannelHttpHandler = microsoftIdentityOptions.BackchannelHttpHandler;
options.Backchannel = microsoftIdentityOptions.Backchannel;
options.DataProtectionProvider = microsoftIdentityOptions.DataProtectionProvider;
options.CallbackPath = microsoftIdentityOptions.CallbackPath;
options.AccessDeniedPath = microsoftIdentityOptions.AccessDeniedPath;
options.ReturnUrlParameter = microsoftIdentityOptions.ReturnUrlParameter;
options.SignInScheme = microsoftIdentityOptions.SignInScheme;
options.RemoteAuthenticationTimeout = microsoftIdentityOptions.RemoteAuthenticationTimeout;
options.Events = microsoftIdentityOptions.Events;
options.SaveTokens = microsoftIdentityOptions.SaveTokens;
options.CorrelationCookie = microsoftIdentityOptions.CorrelationCookie;
options.ClaimsIssuer = microsoftIdentityOptions.ClaimsIssuer;
options.Events = microsoftIdentityOptions.Events;
options.EventsType = microsoftIdentityOptions.EventsType;
options.ForwardDefault = microsoftIdentityOptions.ForwardDefault;
options.ForwardAuthenticate = microsoftIdentityOptions.ForwardAuthenticate;
options.ForwardChallenge = microsoftIdentityOptions.ForwardChallenge;
options.ForwardForbid = microsoftIdentityOptions.ForwardForbid;
options.ForwardSignIn = microsoftIdentityOptions.ForwardSignIn;
options.ForwardSignOut = microsoftIdentityOptions.ForwardSignOut;
options.ForwardDefaultSelector = microsoftIdentityOptions.ForwardDefaultSelector;
}
}
}