forked from openiddict/openiddict-core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOpenIddictClientSystemNetHttpHandlers.cs
More file actions
1161 lines (998 loc) · 56 KB
/
OpenIddictClientSystemNetHttpHandlers.cs
File metadata and controls
1161 lines (998 loc) · 56 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.IO.Compression;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using static OpenIddict.Client.SystemNetHttp.OpenIddictClientSystemNetHttpConstants;
namespace OpenIddict.Client.SystemNetHttp;
[EditorBrowsable(EditorBrowsableState.Never)]
public static partial class OpenIddictClientSystemNetHttpHandlers
{
public static ImmutableArray<OpenIddictClientHandlerDescriptor> DefaultHandlers { get; } =
[
.. Authorization.DefaultHandlers,
.. Device.DefaultHandlers,
.. Discovery.DefaultHandlers,
.. Exchange.DefaultHandlers,
.. Introspection.DefaultHandlers,
.. Revocation.DefaultHandlers,
.. UserInfo.DefaultHandlers
];
/// <summary>
/// Contains the logic responsible for negotiating the best token endpoint client
/// authentication method supported by both the client and the authorization server.
/// </summary>
[Obsolete("This class is obsolete and will be removed in a future version.")]
public sealed class AttachNonDefaultTokenEndpointClientAuthenticationMethod : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireTokenRequest>()
.UseSingletonHandler<AttachNonDefaultTokenEndpointClientAuthenticationMethod>()
.SetOrder(AttachTokenEndpointClientAuthenticationMethod.Descriptor.Order - 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) => ValueTask.CompletedTask;
}
/// <summary>
/// Contains the logic responsible for negotiating the best token binding
/// methods supported by both the client and the authorization server.
/// </summary>
[Obsolete("This class is obsolete and will be removed in a future version.")]
public sealed class AttachNonDefaultUserInfoEndpointTokenBindingMethods : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireUserInfoRequest>()
.UseSingletonHandler<AttachNonDefaultUserInfoEndpointTokenBindingMethods>()
.SetOrder(AttachUserInfoEndpointTokenBindingMethods.Descriptor.Order - 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) => ValueTask.CompletedTask;
}
/// <summary>
/// Contains the logic responsible for negotiating the best device authorization endpoint
/// client authentication method supported by both the client and the authorization server.
/// </summary>
[Obsolete("This class is obsolete and will be removed in a future version.")]
public sealed class AttachNonDefaultDeviceAuthorizationEndpointClientAuthenticationMethod : IOpenIddictClientHandler<ProcessChallengeContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessChallengeContext>()
.AddFilter<RequireDeviceAuthorizationRequest>()
.UseSingletonHandler<AttachNonDefaultDeviceAuthorizationEndpointClientAuthenticationMethod>()
.SetOrder(AttachDeviceAuthorizationEndpointClientAuthenticationMethod.Descriptor.Order - 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessChallengeContext context) => ValueTask.CompletedTask;
}
/// <summary>
/// Contains the logic responsible for negotiating the best pushed authorization endpoint
/// client authentication method supported by both the client and the authorization server.
/// </summary>
[Obsolete("This class is obsolete and will be removed in a future version.")]
public sealed class AttachNonDefaultPushedAuthorizationEndpointClientAuthenticationMethod : IOpenIddictClientHandler<ProcessChallengeContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessChallengeContext>()
.AddFilter<RequirePushedAuthorizationRequest>()
.UseSingletonHandler<AttachNonDefaultPushedAuthorizationEndpointClientAuthenticationMethod>()
.SetOrder(AttachPushedAuthorizationEndpointClientAuthenticationMethod.Descriptor.Order - 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessChallengeContext context) => ValueTask.CompletedTask;
}
/// <summary>
/// Contains the logic responsible for negotiating the best introspection endpoint client
/// authentication method supported by both the client and the authorization server.
/// </summary>
[Obsolete("This class is obsolete and will be removed in a future version.")]
public sealed class AttachNonDefaultIntrospectionEndpointClientAuthenticationMethod : IOpenIddictClientHandler<ProcessIntrospectionContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessIntrospectionContext>()
.AddFilter<RequireIntrospectionRequest>()
.UseSingletonHandler<AttachNonDefaultIntrospectionEndpointClientAuthenticationMethod>()
.SetOrder(AttachIntrospectionEndpointClientAuthenticationMethod.Descriptor.Order - 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessIntrospectionContext context) => ValueTask.CompletedTask;
}
/// <summary>
/// Contains the logic responsible for negotiating the best revocation endpoint client
/// authentication method supported by both the client and the authorization server.
/// </summary>
[Obsolete("This class is obsolete and will be removed in a future version.")]
public sealed class AttachNonDefaultRevocationEndpointClientAuthenticationMethod : IOpenIddictClientHandler<ProcessRevocationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessRevocationContext>()
.AddFilter<RequireRevocationRequest>()
.UseSingletonHandler<AttachNonDefaultRevocationEndpointClientAuthenticationMethod>()
.SetOrder(AttachRevocationEndpointClientAuthenticationMethod.Descriptor.Order - 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessRevocationContext context) => ValueTask.CompletedTask;
}
/// <summary>
/// Contains the logic responsible for creating and attaching a <see cref="HttpClient"/>.
/// </summary>
public sealed class CreateHttpClient<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
private readonly IHttpClientFactory _factory;
public CreateHttpClient(IHttpClientFactory factory)
=> _factory = factory ?? throw new ArgumentNullException(nameof(factory));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<CreateHttpClient<TContext>>()
.SetOrder(int.MinValue + 100_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Note: HttpClientFactory doesn't support flowing a list of properties that can be
// accessed from the HttpClientAction or HttpMessageHandlerBuilderAction delegates
// to dynamically amend the resulting HttpClient or HttpClientHandler instance.
//
// To work around this limitation, the OpenIddict System.Net.Http integration uses
// an async-local context to flow per-instance properties and uses dynamic client
// names to ensure the inner HttpClientHandler is not reused if the context differs.
if (OpenIddictClientSystemNetHttpContext.Current is not null)
{
throw new InvalidOperationException(SR.FormatID0515(nameof(OpenIddictClientSystemNetHttpContext)));
}
try
{
OpenIddictClientSystemNetHttpContext.Current = new()
{
Registration = context.Registration,
LocalCertificate = context.LocalCertificate
};
// Generate a stable identifier representing the current context to ensure the inner
// HttpClientHandler instances are not reused for different operations if the properties
// attached to the context are not identical (e.g different TLS client certificates).
var identifier = OpenIddictClientSystemNetHttpContext.ComputeStableId(OpenIddictClientSystemNetHttpContext.Current);
var client = _factory.CreateClient(
$"{typeof(OpenIddictClientSystemNetHttpOptions).Assembly.GetName().Name}:{identifier}") ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0174));
// Create and store the HttpClient in the transaction properties.
context.Transaction.SetProperty(typeof(HttpClient).FullName!, client);
}
finally
{
OpenIddictClientSystemNetHttpContext.Current = null;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for preparing an HTTP GET request message.
/// </summary>
public sealed class PrepareGetHttpRequest<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<PrepareGetHttpRequest<TContext>>()
.SetOrder(CreateHttpClient<TContext>.Descriptor.Order + 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Store the HttpRequestMessage in the transaction properties.
context.Transaction.SetProperty(typeof(HttpRequestMessage).FullName!,
new HttpRequestMessage(HttpMethod.Get, context.RemoteUri));
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for preparing an HTTP POST request message.
/// </summary>
public sealed class PreparePostHttpRequest<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<PreparePostHttpRequest<TContext>>()
.SetOrder(PrepareGetHttpRequest<TContext>.Descriptor.Order + 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Store the HttpRequestMessage in the transaction properties.
context.Transaction.SetProperty(typeof(HttpRequestMessage).FullName!,
new HttpRequestMessage(HttpMethod.Post, context.RemoteUri));
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for attaching the HTTP version to the HTTP request message.
/// </summary>
public sealed class AttachHttpVersion<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<AttachHttpVersion<TContext>>()
.SetOrder(PreparePostHttpRequest<TContext>.Descriptor.Order + 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
#if SUPPORTS_HTTP_CLIENT_DEFAULT_REQUEST_VERSION || SUPPORTS_HTTP_CLIENT_DEFAULT_REQUEST_VERSION_POLICY
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
var client = context.Transaction.GetHttpClient() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0372));
#if SUPPORTS_HTTP_CLIENT_DEFAULT_REQUEST_VERSION
// If supported, import the HTTP version from the client instance.
request.Version = client.DefaultRequestVersion;
#endif
#if SUPPORTS_HTTP_CLIENT_DEFAULT_REQUEST_VERSION_POLICY
// If supported, import the HTTP version policy from the client instance.
request.VersionPolicy = client.DefaultVersionPolicy;
#endif
#endif
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for attaching the appropriate HTTP
/// Accept-* headers to the HTTP request message to receive JSON responses.
/// </summary>
public sealed class AttachJsonAcceptHeaders<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<AttachJsonAcceptHeaders<TContext>>()
.SetOrder(AttachHttpVersion<TContext>.Descriptor.Order + 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypes.Json));
request.Headers.AcceptCharset.Add(new StringWithQualityHeaderValue(Charsets.Utf8));
// Note: for security reasons, HTTP compression is never opted-in by default. Providers
// that require using HTTP compression can register a custom event handler to send an
// Accept-Encoding header containing the supported algorithms (e.g GZip/Deflate/Brotli).
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for attaching the user agent to the HTTP request.
/// </summary>
public sealed class AttachUserAgentHeader<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
private readonly IOptionsMonitor<OpenIddictClientSystemNetHttpOptions> _options;
public AttachUserAgentHeader(IOptionsMonitor<OpenIddictClientSystemNetHttpOptions> options)
=> _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<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<AttachUserAgentHeader<TContext>>()
.SetOrder(AttachJsonAcceptHeaders<TContext>.Descriptor.Order + 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Some authorization servers are known to aggressively check user agents and encourage
// developers to use unique user agents. While a default user agent is always added,
// the default value doesn't differ accross applications. To reduce the risks of seeing
// requests blocked, a more specific user agent header can be configured by the developer.
// In this case, the value specified by the developer always appears first in the list.
if (_options.CurrentValue.ProductInformation is ProductInfoHeaderValue information)
{
request.Headers.UserAgent.Add(information);
}
// Attach a user agent based on the assembly version of the System.Net.Http integration.
var assembly = typeof(OpenIddictClientSystemNetHttpHandlers).Assembly.GetName();
request.Headers.UserAgent.Add(new ProductInfoHeaderValue(
productName: assembly.Name!,
productVersion: assembly.Version!.ToString()));
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for attaching the contact address to the HTTP request.
/// </summary>
public sealed class AttachFromHeader<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
private readonly IOptionsMonitor<OpenIddictClientSystemNetHttpOptions> _options;
public AttachFromHeader(IOptionsMonitor<OpenIddictClientSystemNetHttpOptions> options)
=> _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<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<AttachFromHeader<TContext>>()
.SetOrder(AttachUserAgentHeader<TContext>.Descriptor.Order + 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Attach the contact address specified in the options, if available.
request.Headers.From = _options.CurrentValue.ContactAddress?.ToString();
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for attaching the client credentials to the HTTP Authorization header.
/// </summary>
public sealed class AttachBasicAuthenticationCredentials<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<AttachBasicAuthenticationCredentials<TContext>>()
.SetOrder(AttachHttpParameters<TContext>.Descriptor.Order - 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(context.Transaction.Request is not null, SR.GetResourceString(SR.ID4008));
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Note: don't overwrite the authorization header if one was already set by another handler.
if (request.Headers.Authorization is null &&
context.ClientAuthenticationMethod is ClientAuthenticationMethods.ClientSecretBasic &&
!string.IsNullOrEmpty(context.Transaction.Request.ClientId))
{
// Important: the credentials MUST be formURL-encoded before being base64-encoded.
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(new StringBuilder()
.Append(EscapeDataString(context.Transaction.Request.ClientId))
.Append(':')
.Append(EscapeDataString(context.Transaction.Request.ClientSecret))
.ToString()));
// Attach the authorization header containing the client credentials to the HTTP request.
request.Headers.Authorization = new AuthenticationHeaderValue(Schemes.Basic, credentials);
// Remove the client credentials from the request payload to ensure they are not sent twice.
context.Transaction.Request.ClientId = context.Transaction.Request.ClientSecret = null;
}
return ValueTask.CompletedTask;
static string? EscapeDataString(string? value)
=> value is not null ? Uri.EscapeDataString(value).Replace("%20", "+") : null;
}
}
/// <summary>
/// Contains the logic responsible for attaching the parameters to the HTTP request.
/// </summary>
public sealed class AttachHttpParameters<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<AttachHttpParameters<TContext>>()
.SetOrder(int.MaxValue - 100_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(context.Transaction.Request is not null, SR.GetResourceString(SR.ID4008));
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
if (context.Transaction.Request.Count is 0)
{
return ValueTask.CompletedTask;
}
// For GET requests, attach the request parameters to the query string by default.
if (request.Method == HttpMethod.Get && request.RequestUri is not null)
{
request.RequestUri = OpenIddictHelpers.AddQueryStringParameters(request.RequestUri,
context.Transaction.Request.GetParameters().ToDictionary(
static parameter => parameter.Key,
static parameter => (StringValues) parameter.Value));
}
// For POST requests, attach the request parameters to the request form by default.
else if (request.Method == HttpMethod.Post)
{
request.Content = new FormUrlEncodedContent(
from parameter in context.Transaction.Request.GetParameters()
let values = (ImmutableArray<string?>?) parameter.Value
where values is not null
from value in values.GetValueOrDefault()
select KeyValuePair.Create(parameter.Key, value));
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for sending the HTTP request to the remote server.
/// </summary>
public sealed class SendHttpRequest<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<SendHttpRequest<TContext>>()
.SetOrder(DecompressResponseContent<TContext>.Descriptor.Order - 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Note: a "using" statement is deliberately used here to dispose of the client in this handler.
using var client = context.Transaction.GetHttpClient() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0372));
HttpResponseMessage response;
try
{
// Note: HttpCompletionOption.ResponseContentRead is deliberately used to force the
// response stream to be buffered so that can it can be read multiple times if needed
// (e.g if the JSON deserialization process fails, the stream is read as a string
// during a second pass a second time for logging/debuggability purposes).
response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead, context.CancellationToken);
}
// If an exception is thrown at this stage, this likely means a persistent network error occurred.
// In this case, log the error details and return a generic error to stop processing the event.
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
{
context.Logger.LogError(6182, exception, SR.GetResourceString(SR.ID6182));
context.Reject(
error: Errors.ServerError,
description: SR.GetResourceString(SR.ID2136),
uri: SR.FormatID8000(SR.ID2136));
return;
}
// Store the HttpResponseMessage in the transaction properties.
context.Transaction.SetProperty(typeof(HttpResponseMessage).FullName!, response ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0175)));
}
}
/// <summary>
/// Contains the logic responsible for disposing of the HTTP request message.
/// </summary>
public sealed class DisposeHttpRequest<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<DisposeHttpRequest<TContext>>()
.SetOrder(int.MaxValue - 100_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
request.Dispose();
// Remove the request from the transaction properties.
context.Transaction.SetProperty<HttpRequestMessage>(typeof(HttpRequestMessage).FullName!, null);
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for decompressing the returned HTTP content.
/// </summary>
public sealed class DecompressResponseContent<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<DecompressResponseContent<TContext>>()
.SetOrder(ExtractJsonHttpResponse<TContext>.Descriptor.Order - 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Note: automatic content decompression can be enabled by constructing an HttpClient wrapping
// a generic HttpClientHandler, a SocketsHttpHandler or a WinHttpHandler instance with the
// AutomaticDecompression property set to the desired algorithms (e.g GZip, Deflate or Brotli).
//
// Unfortunately, while convenient and efficient, relying on this property has a downside:
// setting AutomaticDecompression always overrides the Accept-Encoding header of all requests
// to include the selected algorithms without offering a way to make this behavior opt-in.
// Sadly, using HTTP content compression with transport security enabled has security implications
// that could potentially lead to compression side-channel attacks if the client is used with
// remote endpoints that reflect user-defined data and contain secret values (e.g BREACH attacks).
//
// Since OpenIddict itself cannot safely assume such scenarios will never happen (e.g a token request
// will typically be sent with an authorization code that can be defined by a malicious user and can
// potentially be reflected in the token response depending on the configuration of the remote server),
// it is safer to disable compression by default by not sending an Accept-Encoding header while
// still allowing encoded responses to be processed (e.g StackExchange forces content compression
// for all the supported HTTP APIs even if no Accept-Encoding header is explicitly sent by the client).
//
// For these reasons, OpenIddict doesn't rely on the automatic decompression feature and uses
// a custom event handler to deal with GZip/Deflate/Brotli-encoded responses, so that servers
// that require using HTTP compression can be supported without having to use it for all servers.
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// If no Content-Encoding header was returned, keep the response stream as-is.
if (response.Content is not { Headers.ContentEncoding.Count: > 0 })
{
return;
}
// On iOS, the generic HttpClientHandler type instantiates a NSUrlSessionHandler under the hood.
// NSURLSession is known for enforcing response compression on certain versions of iOS: when
// using this type, an Accept-Encoding header is automatically attached by iOS and the response
// is automatically decompressed. Unfortunately, NSUrlSessionHandler doesn't remove the
// Content-Encoding header from the response, which leads to incorrect results when trying
// to decompress the content a second time. To avoid that, the entire logic used in this
// handler is ignored on iOS if the native HTTP handler (NSUrlSessionHandler) is used.
if (OperatingSystem.IsIOS() &&
AppContext.TryGetSwitch("System.Net.Http.UseNativeHttpHandler", out bool value) && value)
{
return;
}
Stream? stream = null;
// Iterate the returned encodings and wrap the response stream using the specified algorithm.
// If one of the returned algorithms cannot be recognized, immediately return an error.
foreach (var encoding in response.Content.Headers.ContentEncoding.Reverse())
{
if (string.Equals(encoding, ContentEncodings.Identity, StringComparison.OrdinalIgnoreCase))
{
continue;
}
else if (string.Equals(encoding, ContentEncodings.Gzip, StringComparison.OrdinalIgnoreCase))
{
stream ??= await response.Content.ReadAsStreamAsync();
stream = new GZipStream(stream, CompressionMode.Decompress);
}
#if SUPPORTS_ZLIB_COMPRESSION
// Note: some server implementations are known to incorrectly implement the "Deflate" compression
// algorithm and don't wrap the compressed data in a ZLib frame as required by the specifications.
//
// Such implementations are deliberately not supported here. In this case, it is recommended to avoid
// including "deflate" in the Accept-Encoding header if the server is known to be non-compliant.
//
// For more information, read https://www.rfc-editor.org/rfc/rfc9110.html#name-deflate-coding.
else if (string.Equals(encoding, ContentEncodings.Deflate, StringComparison.OrdinalIgnoreCase))
{
stream ??= await response.Content.ReadAsStreamAsync();
stream = new ZLibStream(stream, CompressionMode.Decompress);
}
#endif
#if SUPPORTS_BROTLI_COMPRESSION
else if (string.Equals(encoding, ContentEncodings.Brotli, StringComparison.OrdinalIgnoreCase))
{
stream ??= await response.Content.ReadAsStreamAsync();
stream = new BrotliStream(stream, CompressionMode.Decompress);
}
#endif
else
{
context.Reject(
error: Errors.ServerError,
description: SR.GetResourceString(SR.ID2143),
uri: SR.FormatID8000(SR.ID2143));
return;
}
}
// At this point, if the stream was wrapped, replace the content attached
// to the HTTP response message to use the specified stream transformations.
if (stream is not null)
{
// Note: StreamContent.LoadIntoBufferAsync is deliberately used to force the stream
// content to be buffered so that can it can be read multiple times if needed
// (e.g if the JSON deserialization process fails, the stream is read as a string
// during a second pass a second time for logging/debuggability purposes).
var content = new StreamContent(stream);
await content.LoadIntoBufferAsync();
// Copy the headers from the original content to the new instance.
foreach (var header in response.Content.Headers)
{
content.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
// Reset the Content-Length and Content-Encoding headers to indicate
// the content was successfully decoded using the specified algorithms.
content.Headers.ContentLength = null;
content.Headers.ContentEncoding.Clear();
response.Content = content;
}
}
}
/// <summary>
/// Contains the logic responsible for extracting the response from the JSON-encoded HTTP body.
/// </summary>
public sealed class ExtractJsonHttpResponse<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<ExtractJsonHttpResponse<TContext>>()
.SetOrder(ExtractWwwAuthenticateHeader<TContext>.Descriptor.Order - 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Don't overwrite the response if one was already provided.
if (context.Transaction.Response is not null)
{
return;
}
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// If the returned Content-Type doesn't indicate the response has a JSON payload,
// ignore it and allow other handlers in the pipeline to process the HTTP response.
if (!string.Equals(response.Content.Headers.ContentType?.MediaType,
MediaTypes.Json, StringComparison.OrdinalIgnoreCase) &&
!HasJsonStructuredSyntaxSuffix(response.Content.Headers.ContentType))
{
return;
}
try
{
// Note: ReadFromJsonAsync() automatically validates the content encoding and transparently
// transcodes the response stream if a non-UTF-8 response is returned by the remote server.
context.Transaction.Response = await response.Content.ReadFromJsonAsync(
OpenIddictSerializer.Default.Response, context.CancellationToken);
}
// If an exception is thrown at this stage, this likely means the returned response was not a valid
// JSON response or was not correctly formatted as a JSON object. This typically happens when
// a server error occurs while the JSON response is being generated and returned to the client.
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
{
context.Logger.LogError(6183, exception, SR.GetResourceString(SR.ID6183),
await response.Content.ReadAsStringAsync());
context.Reject(
error: Errors.ServerError,
description: SR.GetResourceString(SR.ID2137),
uri: SR.FormatID8000(SR.ID2137));
return;
}
static bool HasJsonStructuredSyntaxSuffix(MediaTypeHeaderValue? type) =>
// If the length of the media type is less than the expected number of characters needed
// to compose a JSON-derived type (i.e application/*+json), assume the content is not JSON.
type?.MediaType is { Length: >= 18 } &&
// JSON media types MUST always start with "application/".
type.MediaType.AsSpan(0, 12).Equals("application/".AsSpan(), StringComparison.OrdinalIgnoreCase) &&
// JSON media types MUST always end with "+json".
type.MediaType.AsSpan()[^5..].Equals("+json".AsSpan(), StringComparison.OrdinalIgnoreCase);
}
}
/// <summary>
/// Contains the logic responsible for extracting errors from WWW-Authenticate headers.
/// </summary>
public sealed class ExtractWwwAuthenticateHeader<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<ExtractWwwAuthenticateHeader<TContext>>()
.SetOrder(ExtractEmptyHttpResponse<TContext>.Descriptor.Order - 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Don't overwrite the response if one was already provided.
if (context.Transaction.Response is not null)
{
return ValueTask.CompletedTask;
}
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
if (response.Headers.WwwAuthenticate.Count is 0)
{
return ValueTask.CompletedTask;
}
context.Transaction.Response = new OpenIddictResponse(response.Headers.WwwAuthenticate
.Where(static header => !string.IsNullOrEmpty(header.Parameter))
.SelectMany(static header => ParseParameters(header.Parameter!)));
return ValueTask.CompletedTask;
static IEnumerable<KeyValuePair<string, string?>> ParseParameters(string parameter)
{
var index = 0;
while (index < parameter.Length)
{
// Skip leading whitespaces and commas.
while (index < parameter.Length && (char.IsWhiteSpace(parameter[index]) || parameter[index] is ','))
{
index++;
}
// Parse the parameter key.
var start = index;
while (index < parameter.Length && parameter[index] is not ('=' or ','))
{
index++;
}
if (index >= parameter.Length || parameter[index] is ',')
{
break;
}
var key = parameter[start..index].Trim();
// Skip the equals sign.
index++;
while (index < parameter.Length && char.IsWhiteSpace(parameter[index]))
{
index++;
}
// Parse the parameter value.
string value;
if (index < parameter.Length && parameter[index] is '"')
{
// Skip the opening quote.
index++;
var builder = new StringBuilder();
while (index < parameter.Length)
{
if (parameter[index] is '\\' && index + 1 < parameter.Length)
{
builder.Append(parameter[index + 1]);
index += 2;
}
else if (parameter[index] is '"')
{
// Skip the closing quote.
index++;
break;
}
else
{
builder.Append(parameter[index++]);
}
}
value = builder.ToString();
}
else