forked from openiddict/openiddict-core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOpenIddictClientSystemIntegrationHandlers.cs
More file actions
2396 lines (2046 loc) · 119 KB
/
OpenIddictClientSystemIntegrationHandlers.cs
File metadata and controls
2396 lines (2046 loc) · 119 KB
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Net;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using static OpenIddict.Client.SystemIntegration.OpenIddictClientSystemIntegrationConstants;
namespace OpenIddict.Client.SystemIntegration;
[EditorBrowsable(EditorBrowsableState.Never)]
public static partial class OpenIddictClientSystemIntegrationHandlers
{
public static ImmutableArray<OpenIddictClientHandlerDescriptor> DefaultHandlers { get; } =
[
/*
* Top-level request processing:
*/
ResolveRequestUriFromHttpListenerRequest.Descriptor,
ResolveRequestUriFromProtocolActivation.Descriptor,
ResolveRequestUriFromPlatformCallback.Descriptor,
InferEndpointTypeFromDynamicAddress.Descriptor,
RejectUnknownHttpRequests.Descriptor,
/*
* Authentication processing:
*/
WaitMarshalledAuthentication.Descriptor,
RestoreRequestFromMarshalledContext.Descriptor,
RestoreClientRegistrationFromMarshalledContext.Descriptor,
EvaluateValidatedUpfrontTokensForMarshalledContext.Descriptor,
ResolveValidatedStateTokenFromMarshalledContext.Descriptor,
EvaluateValidatedFrontchannelTokensForMarshalledContext.Descriptor,
ResolveValidatedFrontchannelTokensFromMarshalledContext.Descriptor,
EvaluateValidatedBackchannelTokensForMarshalledContext.Descriptor,
DisableStateTokenRedeeming.Descriptor,
DisableTokenRequestSending.Descriptor,
DisableUserInfoRequestSending.Descriptor,
RedirectProtocolActivation.Descriptor,
ResolveRequestForgeryProtection.Descriptor,
CompleteAuthenticationOperation.Descriptor,
UntrackMarshalledAuthenticationOperation.Descriptor,
/*
* Challenge processing:
*/
InferBaseUriFromClientUri.Descriptor,
AttachDynamicPortToRedirectUri.Descriptor,
AttachNonDefaultResponseMode.Descriptor,
AttachInstanceIdentifier.Descriptor,
TrackAuthenticationOperation.Descriptor,
/*
* Sign-out processing:
*/
InferLogoutBaseUriFromClientUri.Descriptor,
AttachDynamicPortToPostLogoutRedirectUri.Descriptor,
AttachLogoutInstanceIdentifier.Descriptor,
TrackLogoutOperation.Descriptor,
/*
* Error processing:
*/
AbortAuthenticationDemand.Descriptor,
.. Authentication.DefaultHandlers,
.. Session.DefaultHandlers
];
/// <summary>
/// Contains the logic responsible for resolving the request URI from the HTTP listener request.
/// Note: this handler is not used when the OpenID Connect request is not handled by the embedded web server.
/// </summary>
public sealed class ResolveRequestUriFromHttpListenerRequest : IOpenIddictClientHandler<ProcessRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessRequestContext>()
.AddFilter<RequireHttpListenerContext>()
.UseSingletonHandler<ResolveRequestUriFromHttpListenerRequest>()
.SetOrder(int.MinValue + 50_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
// When using the OpenIddict client system integration, requests can originate from multiple sources:
//
// - A proper HTTP GET request handled by the embedded web server, when the authorization server
// returns an HTTP 302 response pointing to the local machine (e.g an authorization response).
// In this case, the handling is very similar to what's performed by the web-based OWIN or
// ASP.NET Core hosts and a proper HTTP response can be returned and rendered by the browser.
//
// - A protocol activation triggered when the authorization server returns a HTTP 302 response
// with a redirection address associated with the client application (e.g using a manifest
// or a registry entry). In this case, the redirection is handled by the operating system
// that instantiates the application process and no response can be returned to the browser.
//
// - A protocol activation redirected by another instance of the application using inter-process
// communication. The handling of such activations is similar to direct protocol activations
// and no response can be returned to the browser (that typically stays on the same page).
//
// - A redirection handled transparently by a web-view component (e.g the web authentication
// broker on Windows). In this case, the modal window created by the application or the
// operating system is automatically closed when the specified callback URI is reached
// and there is no way to return a response that would be visible by the user.
//
// OpenIddict unifies these request models by sharing the same request processing pipeline and
// by adapting the logic based on the request type (e.g only protocol activations are redirected
// to other instances and can result in the current instance being terminated by OpenIddict).
(context.BaseUri, context.RequestUri) = context.Transaction.GetHttpListenerContext() switch
{
// Note: unlike the equivalent handler in the ASP.NET Core and OWIN hosts, the URI is
// expected to be always present and absolute, as the embedded web server is configured
// to use "localhost" as the registered prefix, which forces HTTP.sys (or the managed
// .NET implementation on non-Windows operating systems) to automatically reject requests
// that don't include a Host header (e.g HTTP/1.0 requests) or specify an invalid value.
{ Request.Url: { IsAbsoluteUri: true } uri } => (
BaseUri: new UriBuilder(uri) { Path = null, Query = null, Fragment = null }.Uri,
RequestUri: uri),
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0390))
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for resolving the request URI from the protocol activation details.
/// Note: this handler is not used when the OpenID Connect request is not a protocol activation.
/// </summary>
public sealed class ResolveRequestUriFromProtocolActivation : IOpenIddictClientHandler<ProcessRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessRequestContext>()
.AddFilter<RequireProtocolActivation>()
.UseSingletonHandler<ResolveRequestUriFromProtocolActivation>()
.SetOrder(ResolveRequestUriFromHttpListenerRequest.Descriptor.Order + 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
(context.BaseUri, context.RequestUri) = context.Transaction.GetProtocolActivation() switch
{
{ ActivationUri: Uri uri } => (
BaseUri: new UriBuilder(uri) { Path = null, Query = null, Fragment = null }.Uri,
RequestUri: uri),
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0375))
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for resolving the request URI from the platform callback details.
/// Note: this handler is not used when the OpenID Connect request is not a platform callback.
/// </summary>
public sealed class ResolveRequestUriFromPlatformCallback : IOpenIddictClientHandler<ProcessRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessRequestContext>()
.AddFilter<RequirePlatformCallback>()
.UseSingletonHandler<ResolveRequestUriFromPlatformCallback>()
.SetOrder(ResolveRequestUriFromProtocolActivation.Descriptor.Order + 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
(context.BaseUri, context.RequestUri) = context.Transaction.GetPlatformCallback() switch
{
{ CallbackUri: Uri uri } => (
BaseUri: new UriBuilder(uri) { Path = null, Query = null, Fragment = null }.Uri,
RequestUri: uri),
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0393))
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for inferring the endpoint type from the request URI, ignoring
/// the port when comparing the request URI with the endpoint URIs configured in the options.
/// Note: this handler is not used when the OpenID Connect request is not handled by the embedded web server.
/// </summary>
public sealed class InferEndpointTypeFromDynamicAddress : IOpenIddictClientHandler<ProcessRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessRequestContext>()
.AddFilter<RequireHttpListenerContext>()
.UseSingletonHandler<InferEndpointTypeFromDynamicAddress>()
.SetOrder(InferEndpointType.Descriptor.Order + 250)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
// If the base or request URIs couldn't be resolved, don't try to infer the endpoint type.
if (context is not { BaseUri.IsAbsoluteUri: true, RequestUri.IsAbsoluteUri: true })
{
return ValueTask.CompletedTask;
}
// If an endpoint was already inferred by the generic handler, don't override it.
if (context.EndpointType is not OpenIddictClientEndpointType.Unknown)
{
return ValueTask.CompletedTask;
}
context.EndpointType =
Matches(context.Options.RedirectionEndpointUris) ? OpenIddictClientEndpointType.Redirection :
Matches(context.Options.PostLogoutRedirectionEndpointUris) ? OpenIddictClientEndpointType.PostLogoutRedirection :
OpenIddictClientEndpointType.Unknown;
return ValueTask.CompletedTask;
bool Matches(IReadOnlyList<Uri> uris)
{
for (var index = 0; index < uris.Count; index++)
{
var uri = uris[index];
if (uri.IsAbsoluteUri && uri.IsLoopback && uri.IsDefaultPort && Equals(uri, context.RequestUri))
{
return true;
}
}
return false;
}
static bool Equals(Uri left, Uri right) =>
string.Equals(left.Scheme, right.Scheme, StringComparison.OrdinalIgnoreCase) &&
string.Equals(left.Host, right.Host, StringComparison.OrdinalIgnoreCase) &&
//
// Deliberately ignore the port when doing comparisons in this specialized handler.
//
// Note: paths are considered equivalent even if the casing isn't identical or if one of the two
// paths only differs by a trailing slash, which matches the classical behavior seen on ASP.NET,
// Microsoft.Owin/Katana and ASP.NET Core. Developers who prefer a different behavior can remove
// this handler and replace it by a custom version implementing a more strict comparison logic.
(string.Equals(left.AbsolutePath, right.AbsolutePath, StringComparison.OrdinalIgnoreCase) ||
(left.AbsolutePath.Length == right.AbsolutePath.Length + 1 &&
left.AbsolutePath.StartsWith(right.AbsolutePath, StringComparison.OrdinalIgnoreCase) &&
left.AbsolutePath[^1] is '/') ||
(right.AbsolutePath.Length == left.AbsolutePath.Length + 1 &&
right.AbsolutePath.StartsWith(left.AbsolutePath, StringComparison.OrdinalIgnoreCase) &&
right.AbsolutePath[^1] is '/'));
}
}
/// <summary>
/// Contains the logic responsible for rejecting unknown requests handled by the embedded web server, if applicable.
/// Note: this handler is not used when the OpenID Connect request is not handled by the embedded web server.
/// </summary>
public sealed class RejectUnknownHttpRequests : IOpenIddictClientHandler<ProcessRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessRequestContext>()
.AddFilter<RequireHttpListenerContext>()
.UseSingletonHandler<RejectUnknownHttpRequests>()
.SetOrder(InferEndpointTypeFromDynamicAddress.Descriptor.Order + 250)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
// This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpListenerContext()?.Response ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0390));
// Unlike the ASP.NET Core or OWIN hosts, the embedded server instantiated by the system
// integration is not meant to handle requests pointing to user-defined HTTP endpoints.
// At such, reject all HTTP requests whose address doesn't match an OpenIddict endpoint.
if (context.EndpointType is OpenIddictClientEndpointType.Unknown)
{
response.StatusCode = (int) HttpStatusCode.NotFound;
context.HandleRequest();
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for extracting OpenID Connect requests from GET HTTP listener requests.
/// Note: this handler is not used when the OpenID Connect request is not handled by the embedded web server.
/// </summary>
public sealed class ExtractGetHttpListenerRequest<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseValidatingContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpListenerContext>()
.UseSingletonHandler<ExtractGetHttpListenerRequest<TContext>>()
.SetOrder(int.MinValue + 100_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpListenerContext()?.Request ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0390));
// If the incoming request doesn't use GET, reject it.
if (!string.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
context.Logger.LogInformation(6137, SR.GetResourceString(SR.ID6137), request.HttpMethod);
context.Reject(
error: Errors.InvalidRequest,
description: SR.GetResourceString(SR.ID2084),
uri: SR.FormatID8000(SR.ID2084));
return ValueTask.CompletedTask;
}
context.Transaction.Request = request.QueryString.AllKeys.Length switch
{
0 => new OpenIddictRequest(),
_ => new OpenIddictRequest(request.QueryString)
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for extracting OpenID Connect requests from GET or POST HTTP listener requests.
/// Note: this handler is not used when the OpenID Connect request is not handled by the embedded web server.
/// </summary>
public sealed class ExtractGetOrPostHttpListenerRequest<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseValidatingContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpListenerContext>()
.UseSingletonHandler<ExtractGetOrPostHttpListenerRequest<TContext>>()
.SetOrder(ExtractGetHttpListenerRequest<TContext>.Descriptor.Order + 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpListenerContext()?.Request ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0390));
if (string.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
context.Transaction.Request = request.QueryString.AllKeys.Length switch
{
0 => new OpenIddictRequest(),
_ => new OpenIddictRequest(request.QueryString)
};
}
else if (string.Equals(request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase))
{
// See http://openid.net/specs/openid-connect-core-1_0.html#FormSerialization for more information.
if (!MediaTypeHeaderValue.TryParse(request.ContentType, out MediaTypeHeaderValue? type) ||
StringSegment.IsNullOrEmpty(type.MediaType))
{
context.Logger.LogInformation(6138, SR.GetResourceString(SR.ID6138), "Content-Type");
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2081("Content-Type"),
uri: SR.FormatID8000(SR.ID2081));
return;
}
if (!StringSegment.Equals(type.MediaType, "application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
{
context.Logger.LogInformation(6139, SR.GetResourceString(SR.ID6139), "Content-Type", request.ContentType);
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2082("Content-Type"),
uri: SR.FormatID8000(SR.ID2082));
return;
}
// Note: do not allow the unsafe UTF-7 encoding to be used, even if explicitly set.
// If no encoding was set or if the received value is not valid, fall back to UTF-8.
context.Transaction.Request = new OpenIddictRequest(await OpenIddictHelpers.ParseFormAsync(
stream : request.InputStream,
encoding : type.Encoding is { CodePage: not 65000 } encoding ? encoding : Encoding.UTF8,
cancellationToken: CancellationToken.None));
}
else
{
context.Logger.LogInformation(6137, SR.GetResourceString(SR.ID6137), request.HttpMethod);
context.Reject(
error: Errors.InvalidRequest,
description: SR.GetResourceString(SR.ID2084),
uri: SR.FormatID8000(SR.ID2084));
return;
}
}
}
/// <summary>
/// Contains the logic responsible for extracting OpenID Connect requests
/// from the URI of an initial or redirected protocol activation.
/// Note: this handler is not used when the OpenID Connect request is not a protocol activation.
/// </summary>
public sealed class ExtractProtocolActivationParameters<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseValidatingContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireProtocolActivation>()
.UseSingletonHandler<ExtractProtocolActivationParameters<TContext>>()
.SetOrder(ExtractGetOrPostHttpListenerRequest<TContext>.Descriptor.Order + 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
if (context.Transaction.GetProtocolActivation() is not { ActivationUri: Uri uri })
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0375));
}
var parameters = new Dictionary<string, StringValues>(StringComparer.Ordinal);
if (!string.IsNullOrEmpty(uri.Query))
{
foreach (var parameter in OpenIddictHelpers.ParseQuery(uri.Query))
{
parameters[parameter.Key] = parameter.Value;
}
}
// Note: the fragment is always processed after the query string to ensure that
// parameters extracted from the fragment are preferred to parameters extracted
// from the query string when they are present in both parts.
if (!string.IsNullOrEmpty(uri.Fragment))
{
foreach (var parameter in OpenIddictHelpers.ParseFragment(uri.Fragment))
{
parameters[parameter.Key] = parameter.Value;
}
}
context.Transaction.Request = new OpenIddictRequest(parameters);
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for extracting OpenID Connect requests from the URI of a platform callback.
/// Note: this handler is not used when the OpenID Connect request is not a platform callback.
/// </summary>
public sealed class ExtractPlatformCallbackParameters<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseValidatingContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequirePlatformCallback>()
.UseSingletonHandler<ExtractPlatformCallbackParameters<TContext>>()
.SetOrder(ExtractProtocolActivationParameters<TContext>.Descriptor.Order + 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
if (context.Transaction.GetPlatformCallback() is not OpenIddictClientSystemIntegrationPlatformCallback callback)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0393));
}
context.Transaction.Request = new OpenIddictRequest(callback.Parameters);
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for waiting for the marshalled authentication operation to complete, if applicable.
/// </summary>
public sealed class WaitMarshalledAuthentication : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
private readonly OpenIddictClientSystemIntegrationMarshal _marshal;
private readonly IOptionsMonitor<OpenIddictClientSystemIntegrationOptions> _options;
public WaitMarshalledAuthentication(
OpenIddictClientSystemIntegrationMarshal marshal,
IOptionsMonitor<OpenIddictClientSystemIntegrationOptions> options)
{
_marshal = marshal ?? throw new ArgumentNullException(nameof(marshal));
_options = options ?? throw new ArgumentNullException(nameof(options));
}
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireAuthenticationNonce>()
.UseSingletonHandler<WaitMarshalledAuthentication>()
.SetOrder(ValidateAuthenticationDemand.Descriptor.Order + 250)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(!string.IsNullOrEmpty(context.Nonce), SR.GetResourceString(SR.ID4019));
// Skip the marshalling logic entirely if the operation is not tracked.
if (!_marshal.IsTracked(context.Nonce))
{
return;
}
// Allow a single authentication operation at the same time with the same nonce.
if (!await _marshal.TryAcquireLockAsync(context.Nonce, context.CancellationToken))
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0379));
}
// At this point, the user authentication demand cannot complete until the authorization response has been
// returned to the redirection endpoint (materialized as a registered protocol activation URI) and handled
// by OpenIddict via the ProcessRequest event. Since it is asynchronous by nature, this process requires
// using a signal mechanism to unblock the authentication operation once it is complete. For that, the
// marshal uses a TaskCompletionSource (one per authentication) that will be automatically completed or
// aborted by a specialized event handler as part of the ProcessRequest/ProcessError events processing.
try
{
// To ensure pending authentication operations for which no response is received are not tracked
// indefinitely, a CancellationTokenSource with a static timeout is used even if the cancellation
// token specified by the user is never marked as canceled: if the authentication is not completed
// when the timeout is reached, the operation will be considered canceled and removed from the list.
using var source = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken);
source.CancelAfter(_options.CurrentValue.AuthenticationTimeout);
if (!await _marshal.TryWaitForCompletionAsync(context.Nonce, source.Token) ||
!_marshal.TryGetResult(context.Nonce, out ProcessAuthenticationContext? notification))
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0383));
}
if (notification.IsRequestHandled)
{
context.HandleRequest();
return;
}
else if (notification.IsRequestSkipped)
{
context.SkipRequest();
return;
}
else if (notification.IsRejected)
{
context.Reject(
error: notification.Error ?? Errors.InvalidRequest,
description: notification.ErrorDescription,
uri: notification.ErrorUri);
return;
}
}
// If the operation failed due to the timeout, it's likely the TryRemove() method
// won't be called, so the tracked context is manually removed before re-throwing.
catch (OperationCanceledException) when (_marshal.TryRemove(context.Nonce))
{
throw;
}
}
}
/// <summary>
/// Contains the logic responsible for restoring the request from the marshalled authentication context, if applicable.
/// </summary>
public sealed class RestoreRequestFromMarshalledContext : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
private readonly OpenIddictClientSystemIntegrationMarshal _marshal;
public RestoreRequestFromMarshalledContext(OpenIddictClientSystemIntegrationMarshal marshal)
=> _marshal = marshal ?? throw new ArgumentNullException(nameof(marshal));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireAuthenticationNonce>()
.UseSingletonHandler<RestoreRequestFromMarshalledContext>()
.SetOrder(WaitMarshalledAuthentication.Descriptor.Order + 250)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(!string.IsNullOrEmpty(context.Nonce), SR.GetResourceString(SR.ID4019));
context.Request = context.EndpointType switch
{
// When the authentication demand is marshalled from a different context, restore the request from the
// other instance so that custom parameters can be resolved from the marshalled context, if necessary.
OpenIddictClientEndpointType.Unknown when _marshal.TryGetResult(context.Nonce, out var notification)
=> notification.Request,
_ => context.Request
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for restoring the client registration and
/// configuration from the marshalled authentication context, if applicable.
/// </summary>
public sealed class RestoreClientRegistrationFromMarshalledContext : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
private readonly OpenIddictClientSystemIntegrationMarshal _marshal;
public RestoreClientRegistrationFromMarshalledContext(OpenIddictClientSystemIntegrationMarshal marshal)
=> _marshal = marshal ?? throw new ArgumentNullException(nameof(marshal));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireAuthenticationNonce>()
.UseSingletonHandler<RestoreClientRegistrationFromMarshalledContext>()
.SetOrder(ResolveClientRegistrationFromAuthenticationContext.Descriptor.Order - 250)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(!string.IsNullOrEmpty(context.Nonce), SR.GetResourceString(SR.ID4019));
(context.Configuration, context.Registration) = context.EndpointType switch
{
// When the authentication demand is marshalled from a different context,
// restore the registration and configuration from the other instance.
OpenIddictClientEndpointType.Unknown when _marshal.TryGetResult(context.Nonce, out var notification)
=> (notification.Configuration, notification.Registration),
_ => (context.Configuration, context.Registration)
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for determining the types of
/// tokens to validate upfront when the context is marshalled.
/// </summary>
public sealed class EvaluateValidatedUpfrontTokensForMarshalledContext : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
private readonly OpenIddictClientSystemIntegrationMarshal _marshal;
public EvaluateValidatedUpfrontTokensForMarshalledContext(OpenIddictClientSystemIntegrationMarshal marshal)
=> _marshal = marshal ?? throw new ArgumentNullException(nameof(marshal));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireAuthenticationNonce>()
.UseSingletonHandler<EvaluateValidatedUpfrontTokensForMarshalledContext>()
.SetOrder(EvaluateValidatedUpfrontTokens.Descriptor.Order + 250)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(!string.IsNullOrEmpty(context.Nonce), SR.GetResourceString(SR.ID4019));
// When the authentication demand is marshalled from a different context, always
// extract and validate the state token to ensure the authentication details
// contained in the state token principal can be used to validate the operation.
if (context.EndpointType is OpenIddictClientEndpointType.Unknown && _marshal.IsTracked(context.Nonce))
{
context.ExtractStateToken = context.RequireStateToken = true;
context.ValidateStateToken = context.RejectStateToken = true;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for resolving the state token to validate upfront from the marshalled context.
/// </summary>
public sealed class ResolveValidatedStateTokenFromMarshalledContext : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
private readonly OpenIddictClientSystemIntegrationMarshal _marshal;
public ResolveValidatedStateTokenFromMarshalledContext(OpenIddictClientSystemIntegrationMarshal marshal)
=> _marshal = marshal ?? throw new ArgumentNullException(nameof(marshal));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireAuthenticationNonce>()
.UseSingletonHandler<ResolveValidatedStateTokenFromMarshalledContext>()
.SetOrder(ResolveValidatedStateToken.Descriptor.Order + 250)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(!string.IsNullOrEmpty(context.Nonce), SR.GetResourceString(SR.ID4019));
context.StateToken = context.EndpointType switch
{
// When the authentication demand is marshalled from a different context,
// always restore the state token from the instance that extracted it.
OpenIddictClientEndpointType.Unknown when _marshal.TryGetResult(context.Nonce, out var notification)
=> notification.StateToken,
_ => null
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for determining the set of
/// frontchannel tokens to validate when the context is marshalled.
/// </summary>
public sealed class EvaluateValidatedFrontchannelTokensForMarshalledContext : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
private readonly OpenIddictClientSystemIntegrationMarshal _marshal;
public EvaluateValidatedFrontchannelTokensForMarshalledContext(OpenIddictClientSystemIntegrationMarshal marshal)
=> _marshal = marshal ?? throw new ArgumentNullException(nameof(marshal));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireAuthenticationNonce>()
.UseSingletonHandler<EvaluateValidatedFrontchannelTokensForMarshalledContext>()
.SetOrder(EvaluateValidatedFrontchannelTokens.Descriptor.Order + 250)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(!string.IsNullOrEmpty(context.Nonce), SR.GetResourceString(SR.ID4019));
// When the authentication demand is expected to be marshalled to a different context,
// always skip the validation of all the frontchannel tokens by default as the security
// principals they contain are not needed to marshal the authentication demand.
if (context.EndpointType is
OpenIddictClientEndpointType.Redirection or
OpenIddictClientEndpointType.PostLogoutRedirection && _marshal.IsTracked(context.Nonce))
{
context.ValidateAuthorizationCode = context.RejectAuthorizationCode = false;
context.ValidateFrontchannelAccessToken = context.RejectFrontchannelAccessToken = false;
context.ValidateFrontchannelIdentityToken = context.RejectFrontchannelIdentityToken = false;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for resolving the frontchannel tokens from the marshalled context.
/// </summary>
public sealed class ResolveValidatedFrontchannelTokensFromMarshalledContext : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
private readonly OpenIddictClientSystemIntegrationMarshal _marshal;
public ResolveValidatedFrontchannelTokensFromMarshalledContext(OpenIddictClientSystemIntegrationMarshal marshal)
=> _marshal = marshal ?? throw new ArgumentNullException(nameof(marshal));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireAuthenticationNonce>()
.UseSingletonHandler<ResolveValidatedFrontchannelTokensFromMarshalledContext>()
.SetOrder(ResolveValidatedFrontchannelTokens.Descriptor.Order + 250)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(!string.IsNullOrEmpty(context.Nonce), SR.GetResourceString(SR.ID4019));
// When the authentication context is marshalled, restore the frontchannel tokens from the other instance.
if (context.EndpointType is OpenIddictClientEndpointType.Unknown &&
_marshal.TryGetResult(context.Nonce, out var notification))
{
context.AuthorizationCode = notification.AuthorizationCode;
context.FrontchannelAccessToken = notification.FrontchannelAccessToken;
context.FrontchannelAccessTokenExpirationDate = notification.FrontchannelAccessTokenExpirationDate;
context.FrontchannelIdentityToken = notification.FrontchannelIdentityToken;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for determining the set of
/// backchannel tokens to validate when the context is marshalled.
/// </summary>
public sealed class EvaluateValidatedBackchannelTokensForMarshalledContext : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
private readonly OpenIddictClientSystemIntegrationMarshal _marshal;
public EvaluateValidatedBackchannelTokensForMarshalledContext(OpenIddictClientSystemIntegrationMarshal marshal)
=> _marshal = marshal ?? throw new ArgumentNullException(nameof(marshal));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireAuthenticationNonce>()
.UseSingletonHandler<EvaluateValidatedBackchannelTokensForMarshalledContext>()
.SetOrder(EvaluateValidatedBackchannelTokens.Descriptor.Order + 250)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(!string.IsNullOrEmpty(context.Nonce), SR.GetResourceString(SR.ID4019));
// When the authentication demand is expected to be marshalled to a different context,
// always skip the validation of all the backchannel tokens by default as the security
// principals they contain are not needed to marshal the authentication demand.
if (context.EndpointType is
OpenIddictClientEndpointType.Redirection or
OpenIddictClientEndpointType.PostLogoutRedirection && _marshal.IsTracked(context.Nonce))
{
context.ValidateBackchannelAccessToken = context.RejectBackchannelAccessToken = false;
context.ValidateBackchannelIdentityToken = context.RejectBackchannelIdentityToken = false;
context.ValidateIssuedToken = context.RejectIssuedToken = false;
context.ValidateRefreshToken = context.RejectRefreshToken = false;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for disabling the redeeming of the state token, if applicable.
/// </summary>
public sealed class DisableStateTokenRedeeming : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
private readonly OpenIddictClientSystemIntegrationMarshal _marshal;
public DisableStateTokenRedeeming(OpenIddictClientSystemIntegrationMarshal marshal)
=> _marshal = marshal ?? throw new ArgumentNullException(nameof(marshal));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireAuthenticationNonce>()
.UseSingletonHandler<DisableStateTokenRedeeming>()
.SetOrder(RedeemStateTokenEntry.Descriptor.Order - 250)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(!string.IsNullOrEmpty(context.Nonce), SR.GetResourceString(SR.ID4019));
context.DisableStateTokenRedeeming = context.EndpointType switch
{
// When the authentication demand is expected to be marshalled to a different context,
// disable the redeeming of the state token to ensure it is not in an invalid state
// when the marshalled authentication demand is processed by the other instance.
OpenIddictClientEndpointType.Redirection or