/
WsFederationHandler.cs
428 lines (371 loc) · 16.5 KB
/
WsFederationHandler.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Linq;
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Protocols.WsFederation;
using Microsoft.IdentityModel.Tokens;
namespace Microsoft.AspNetCore.Authentication.WsFederation;
/// <summary>
/// A per-request authentication handler for the WsFederation.
/// </summary>
public class WsFederationHandler : RemoteAuthenticationHandler<WsFederationOptions>, IAuthenticationSignOutHandler
{
private const string CorrelationProperty = ".xsrf";
private WsFederationConfiguration? _configuration;
/// <summary>
/// Creates a new WsFederationAuthenticationHandler
/// </summary>
/// <param name="options"></param>
/// <param name="encoder"></param>
/// <param name="clock"></param>
/// <param name="logger"></param>
public WsFederationHandler(IOptionsMonitor<WsFederationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
/// <summary>
/// The handler calls methods on the events which give the application control at certain points where processing is occurring.
/// If it is not provided a default instance is supplied which does nothing when the methods are called.
/// </summary>
protected new WsFederationEvents Events
{
get { return (WsFederationEvents)base.Events; }
set { base.Events = value; }
}
/// <summary>
/// Creates a new instance of the events instance.
/// </summary>
/// <returns>A new instance of the events instance.</returns>
protected override Task<object> CreateEventsAsync() => Task.FromResult<object>(new WsFederationEvents());
/// <summary>
/// Overridden to handle remote signout requests
/// </summary>
/// <returns><see langword="true" /> if request processing should stop.</returns>
public override Task<bool> HandleRequestAsync()
{
// RemoteSignOutPath and CallbackPath may be the same, fall through if the message doesn't match.
if (Options.RemoteSignOutPath.HasValue && Options.RemoteSignOutPath == Request.Path && HttpMethods.IsGet(Request.Method)
&& string.Equals(Request.Query[WsFederationConstants.WsFederationParameterNames.Wa],
WsFederationConstants.WsFederationActions.SignOutCleanup, StringComparison.OrdinalIgnoreCase))
{
// We've received a remote sign-out request
return HandleRemoteSignOutAsync();
}
return base.HandleRequestAsync();
}
/// <summary>
/// Handles Challenge
/// </summary>
/// <returns></returns>
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
if (_configuration == null)
{
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
}
// Save the original challenge URI so we can redirect back to it when we're done.
if (string.IsNullOrEmpty(properties.RedirectUri))
{
properties.RedirectUri = OriginalPathBase + OriginalPath + Request.QueryString;
}
var wsFederationMessage = new WsFederationMessage()
{
IssuerAddress = _configuration.TokenEndpoint ?? string.Empty,
Wtrealm = Options.Wtrealm,
Wa = WsFederationConstants.WsFederationActions.SignIn,
};
if (!string.IsNullOrEmpty(Options.Wreply))
{
wsFederationMessage.Wreply = Options.Wreply;
}
else
{
wsFederationMessage.Wreply = BuildRedirectUri(Options.CallbackPath);
}
GenerateCorrelationId(properties);
var redirectContext = new RedirectContext(Context, Scheme, Options, properties)
{
ProtocolMessage = wsFederationMessage
};
await Events.RedirectToIdentityProvider(redirectContext);
if (redirectContext.Handled)
{
return;
}
wsFederationMessage = redirectContext.ProtocolMessage;
if (!string.IsNullOrEmpty(wsFederationMessage.Wctx))
{
properties.Items[WsFederationDefaults.UserstatePropertiesKey] = wsFederationMessage.Wctx;
}
wsFederationMessage.Wctx = Uri.EscapeDataString(Options.StateDataFormat.Protect(properties));
var redirectUri = wsFederationMessage.CreateSignInUrl();
if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
{
Logger.MalformedRedirectUri(redirectUri);
}
Response.Redirect(redirectUri);
}
/// <summary>
/// Invoked to process incoming authentication messages.
/// </summary>
/// <returns></returns>
protected override async Task<HandleRequestResult> HandleRemoteAuthenticateAsync()
{
WsFederationMessage? wsFederationMessage = null;
AuthenticationProperties? properties = null;
// assumption: if the ContentType is "application/x-www-form-urlencoded" it should be safe to read as it is small.
if (HttpMethods.IsPost(Request.Method)
&& !string.IsNullOrEmpty(Request.ContentType)
// May have media/type; charset=utf-8, allow partial match.
&& Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)
&& Request.Body.CanRead)
{
var form = await Request.ReadFormAsync(Context.RequestAborted);
// ToArray handles the StringValues.IsNullOrEmpty case. We assume non-empty Value does not contain null elements.
#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
wsFederationMessage = new WsFederationMessage(form.Select(pair => new KeyValuePair<string, string[]>(pair.Key, pair.Value.ToArray())));
#pragma warning restore CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
}
if (wsFederationMessage == null || !wsFederationMessage.IsSignInMessage)
{
if (Options.SkipUnrecognizedRequests)
{
// Not for us?
return HandleRequestResult.SkipHandler();
}
return HandleRequestResults.NoMessage;
}
try
{
// Retrieve our cached redirect uri
var state = wsFederationMessage.Wctx;
// WsFed allows for uninitiated logins, state may be missing. See AllowUnsolicitedLogins.
properties = Options.StateDataFormat.Unprotect(state);
if (properties == null)
{
if (!Options.AllowUnsolicitedLogins)
{
return HandleRequestResults.UnsolicitedLoginsNotAllowed;
}
}
else
{
// Extract the user state from properties and reset.
properties.Items.TryGetValue(WsFederationDefaults.UserstatePropertiesKey, out var userState);
wsFederationMessage.Wctx = userState;
}
var messageReceivedContext = new MessageReceivedContext(Context, Scheme, Options, properties)
{
ProtocolMessage = wsFederationMessage
};
await Events.MessageReceived(messageReceivedContext);
if (messageReceivedContext.Result != null)
{
return messageReceivedContext.Result;
}
wsFederationMessage = messageReceivedContext.ProtocolMessage;
properties = messageReceivedContext.Properties!; // Provides a new instance if not set.
// If state did flow from the challenge then validate it. See AllowUnsolicitedLogins above.
if (properties.Items.TryGetValue(CorrelationProperty, out string? correlationId)
&& !ValidateCorrelationId(properties))
{
return HandleRequestResult.Fail("Correlation failed.", properties);
}
if (wsFederationMessage.Wresult == null)
{
Logger.SignInWithoutWResult();
return HandleRequestResult.Fail(Resources.SignInMessageWresultIsMissing, properties);
}
var token = wsFederationMessage.GetToken();
if (string.IsNullOrEmpty(token))
{
Logger.SignInWithoutToken();
return HandleRequestResult.Fail(Resources.SignInMessageTokenIsMissing, properties);
}
var securityTokenReceivedContext = new SecurityTokenReceivedContext(Context, Scheme, Options, properties)
{
ProtocolMessage = wsFederationMessage
};
await Events.SecurityTokenReceived(securityTokenReceivedContext);
if (securityTokenReceivedContext.Result != null)
{
return securityTokenReceivedContext.Result;
}
wsFederationMessage = securityTokenReceivedContext.ProtocolMessage;
properties = messageReceivedContext.Properties!;
if (_configuration == null)
{
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
}
// Copy and augment to avoid cross request race conditions for updated configurations.
var tvp = Options.TokenValidationParameters.Clone();
var issuers = new[] { _configuration.Issuer };
tvp.ValidIssuers = (tvp.ValidIssuers == null ? issuers : tvp.ValidIssuers.Concat(issuers));
tvp.IssuerSigningKeys = (tvp.IssuerSigningKeys == null ? _configuration.SigningKeys : tvp.IssuerSigningKeys.Concat(_configuration.SigningKeys));
ClaimsPrincipal? principal = null;
SecurityToken? parsedToken = null;
foreach (var validator in Options.SecurityTokenHandlers)
{
if (validator.CanReadToken(token))
{
principal = validator.ValidateToken(token, tvp, out parsedToken);
break;
}
}
if (principal == null)
{
throw new SecurityTokenException(Resources.Exception_NoTokenValidatorFound);
}
if (Options.UseTokenLifetime && parsedToken != null)
{
// Override any session persistence to match the token lifetime.
var issued = parsedToken.ValidFrom;
if (issued != DateTime.MinValue)
{
properties.IssuedUtc = issued.ToUniversalTime();
}
var expires = parsedToken.ValidTo;
if (expires != DateTime.MinValue)
{
properties.ExpiresUtc = expires.ToUniversalTime();
}
properties.AllowRefresh = false;
}
var securityTokenValidatedContext = new SecurityTokenValidatedContext(Context, Scheme, Options, principal, properties)
{
ProtocolMessage = wsFederationMessage,
SecurityToken = parsedToken,
};
await Events.SecurityTokenValidated(securityTokenValidatedContext);
if (securityTokenValidatedContext.Result != null)
{
return securityTokenValidatedContext.Result;
}
// Flow possible changes
principal = securityTokenValidatedContext.Principal!;
properties = securityTokenValidatedContext.Properties;
return HandleRequestResult.Success(new AuthenticationTicket(principal, properties, Scheme.Name));
}
catch (Exception exception)
{
Logger.ExceptionProcessingMessage(exception);
// Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the notification.
if (Options.RefreshOnIssuerKeyNotFound && exception is SecurityTokenSignatureKeyNotFoundException)
{
Options.ConfigurationManager.RequestRefresh();
}
var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
{
ProtocolMessage = wsFederationMessage,
Exception = exception
};
await Events.AuthenticationFailed(authenticationFailedContext);
if (authenticationFailedContext.Result != null)
{
return authenticationFailedContext.Result;
}
return HandleRequestResult.Fail(exception, properties);
}
}
/// <summary>
/// Handles Signout
/// </summary>
/// <returns></returns>
public virtual async Task SignOutAsync(AuthenticationProperties? properties)
{
var target = ResolveTarget(Options.ForwardSignOut);
if (target != null)
{
await Context.SignOutAsync(target, properties);
return;
}
if (_configuration == null)
{
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
}
var wsFederationMessage = new WsFederationMessage()
{
IssuerAddress = _configuration.TokenEndpoint ?? string.Empty,
Wtrealm = Options.Wtrealm,
Wa = WsFederationConstants.WsFederationActions.SignOut,
};
// Set Wreply in order:
// 1. properties.Redirect
// 2. Options.SignOutWreply
// 3. Options.Wreply
if (properties != null && !string.IsNullOrEmpty(properties.RedirectUri))
{
wsFederationMessage.Wreply = BuildRedirectUriIfRelative(properties.RedirectUri);
}
else if (!string.IsNullOrEmpty(Options.SignOutWreply))
{
wsFederationMessage.Wreply = BuildRedirectUriIfRelative(Options.SignOutWreply);
}
else if (!string.IsNullOrEmpty(Options.Wreply))
{
wsFederationMessage.Wreply = BuildRedirectUriIfRelative(Options.Wreply);
}
var redirectContext = new RedirectContext(Context, Scheme, Options, properties)
{
ProtocolMessage = wsFederationMessage
};
await Events.RedirectToIdentityProvider(redirectContext);
if (!redirectContext.Handled)
{
var redirectUri = redirectContext.ProtocolMessage.CreateSignOutUrl();
if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
{
Logger.MalformedRedirectUri(redirectUri);
}
Response.Redirect(redirectUri);
}
}
/// <summary>
/// Handles wsignoutcleanup1.0 messages sent to the RemoteSignOutPath
/// </summary>
/// <returns></returns>
protected virtual async Task<bool> HandleRemoteSignOutAsync()
{
// ToArray handles the StringValues.IsNullOrEmpty case. We assume non-empty Value does not contain null elements.
#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
var message = new WsFederationMessage(Request.Query.Select(pair => new KeyValuePair<string, string[]>(pair.Key, pair.Value.ToArray())));
#pragma warning restore CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
var remoteSignOutContext = new RemoteSignOutContext(Context, Scheme, Options, message);
await Events.RemoteSignOut(remoteSignOutContext);
if (remoteSignOutContext.Result != null)
{
if (remoteSignOutContext.Result.Handled)
{
Logger.RemoteSignOutHandledResponse();
return true;
}
if (remoteSignOutContext.Result.Skipped)
{
Logger.RemoteSignOutSkipped();
return false;
}
}
Logger.RemoteSignOut();
await Context.SignOutAsync(Options.SignOutScheme);
return true;
}
/// <summary>
/// Build a redirect path if the given path is a relative path.
/// </summary>
private string BuildRedirectUriIfRelative(string uri)
{
if (string.IsNullOrEmpty(uri))
{
return uri;
}
if (!uri.StartsWith("/", StringComparison.Ordinal))
{
return uri;
}
return BuildRedirectUri(uri);
}
}