forked from openiddict/openiddict-core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOpenIddictClientWebIntegrationHandlers.cs
More file actions
2204 lines (1871 loc) · 113 KB
/
OpenIddictClientWebIntegrationHandlers.cs
File metadata and controls
2204 lines (1871 loc) · 113 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.Security.Claims;
using System.Text;
using System.Text.Json;
using static OpenIddict.Client.WebIntegration.OpenIddictClientWebIntegrationConstants;
namespace OpenIddict.Client.WebIntegration;
[EditorBrowsable(EditorBrowsableState.Never)]
public static partial class OpenIddictClientWebIntegrationHandlers
{
public static ImmutableArray<OpenIddictClientHandlerDescriptor> DefaultHandlers { get; } =
[
/*
* Authentication processing:
*/
DisableIssuerParameterValidation.Descriptor,
ValidateRedirectionRequestSignature.Descriptor,
HandleNonStandardFrontchannelErrorResponse.Descriptor,
ValidateNonStandardParameters.Descriptor,
OverrideTokenEndpointClientAuthenticationMethod.Descriptor,
OverrideTokenEndpoint.Descriptor,
AttachNonStandardClientAssertionClaims.Descriptor,
OverrideScopes.Descriptor,
AttachAdditionalTokenRequestParameters.Descriptor,
AttachTokenRequestNonStandardClientCredentials.Descriptor,
AdjustRedirectUriInTokenRequest.Descriptor,
OverrideValidatedBackchannelTokens.Descriptor,
DisableBackchannelIdentityTokenNonceValidation.Descriptor,
OverrideUserInfoRetrieval.Descriptor,
OverrideUserInfoValidation.Descriptor,
OverrideUserInfoEndpoint.Descriptor,
AttachAdditionalUserInfoRequestParameters.Descriptor,
PopulateUserInfoTokenPrincipalFromTokenResponse.Descriptor,
MapCustomWebServicesFederationClaims.Descriptor,
/*
* Challenge processing:
*/
ValidateChallengeProperties.Descriptor,
OverrideAuthorizationEndpoint.Descriptor,
OverrideResponseMode.Descriptor,
FormatNonStandardScopeParameter.Descriptor,
IncludeStateParameterInRedirectUri.Descriptor,
AttachAdditionalChallengeParameters.Descriptor,
/*
* Revocation processing:
*/
OverrideRevocationEndpointClientAuthenticationMethod.Descriptor,
AttachNonStandardRevocationClientAssertionClaims.Descriptor,
AttachRevocationRequestNonStandardClientCredentials.Descriptor,
.. Authentication.DefaultHandlers,
.. Device.DefaultHandlers,
.. Discovery.DefaultHandlers,
.. Exchange.DefaultHandlers,
.. Introspection.DefaultHandlers,
.. Protection.DefaultHandlers,
.. Revocation.DefaultHandlers,
.. UserInfo.DefaultHandlers
];
/// <summary>
/// Contains the logic responsible for disabling the issuer parameter validation for the providers that require it.
/// </summary>
public sealed class DisableIssuerParameterValidation : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.UseSingletonHandler<DisableIssuerParameterValidation>()
.SetOrder(ValidateIssuerParameter.Descriptor.Order - 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
context.DisableIssuerParameterValidation = context.Registration.ProviderType switch
{
// Google is currently rolling out a change that causes the "iss" authorization response
// parameter to be returned without the "authorization_response_iss_parameter_supported"
// flag being advertised in the provider metadata. Since OpenIddict rejects authorization
// responses that contain an issuer if "authorization_response_iss_parameter_supported" is
// not explicitly set to true, validation must be disabled until the deployment is complete.
//
// See https://github.com/openiddict/openiddict-core/issues/2428 for more information.
ProviderTypes.Google when context.Request.HasParameter(Parameters.Iss) &&
context.Configuration.AuthorizationResponseIssParameterSupported is not true => true,
_ => context.DisableIssuerParameterValidation
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for validating the signature or message authentication
/// code attached to the redirection request for the providers that require it.
/// </summary>
public sealed class ValidateRedirectionRequestSignature : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireRedirectionRequest>()
.UseSingletonHandler<ValidateRedirectionRequestSignature>()
.SetOrder(ValidateIssuerParameter.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Shopify returns custom/non-standard parameters like the name of the shop for which the
// installation request was initiated. To prevent these parameters from being tampered with,
// a "hmac" parameter is added by Shopify alongside a "timestamp" parameter containing the
// UNIX-formatted date at which the authorization response was generated. While this doesn't
// by itself protect against replayed HMACs, the HMAC always includes the "state" parameter,
// which is itself protected against replay attacks as state tokens are automatically marked
// as redeemed by OpenIddict when they are returned to the redirection endpoint.
//
// For more information, see
// https://shopify.dev/docs/apps/auth/oauth/getting-started#step-2-verify-the-installation-request.
if (context.Registration.ProviderType is ProviderTypes.Shopify &&
!string.IsNullOrEmpty(context.Registration.ClientSecret))
{
var signature = (string?) context.Request["hmac"];
if (string.IsNullOrEmpty(signature))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2029("hmac"),
uri: SR.FormatID8000(SR.ID2029));
return ValueTask.CompletedTask;
}
var builder = new StringBuilder();
// Note: the "hmac" parameter MUST be ignored and the remaining parameters MUST be sorted alphabetically.
//
// See https://shopify.dev/docs/apps/auth/oauth/getting-started#remove-the-hmac-parameter-from-the-query-string
// for more information.
foreach (var (name, value) in
from parameter in OpenIddictHelpers.ParseQuery(context.RequestUri!.Query)
where !string.IsNullOrEmpty(parameter.Key)
where !string.Equals(parameter.Key, "hmac", StringComparison.Ordinal)
orderby parameter.Key ascending
from value in parameter.Value
select (Name: parameter.Key, Value: value))
{
if (builder.Length is > 0)
{
builder.Append('&');
}
builder.Append(Uri.EscapeDataString(name));
if (!string.IsNullOrEmpty(value))
{
builder.Append('=');
builder.Append(Uri.EscapeDataString(value));
}
}
// Compare the received HMAC (represented as an hexadecimal string) and the HMAC computed
// locally from the concatenated query string: if the two don't match, return an error.
//
// Note: to prevent timing attacks, a time-constant comparer is always used.
try
{
if (!OpenIddictHelpers.FixedTimeEquals(
left : Convert.FromHexString(signature),
right: OpenIddictHelpers.ComputeSha256MessageAuthenticationCode(
key : Encoding.UTF8.GetBytes(context.Registration.ClientSecret),
data: Encoding.UTF8.GetBytes(builder.ToString()))))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2052("hmac"),
uri: SR.FormatID8000(SR.ID2052));
return ValueTask.CompletedTask;
}
}
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2052("hmac"),
uri: SR.FormatID8000(SR.ID2052));
return ValueTask.CompletedTask;
}
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for handling non-standard
/// authorization errors for the providers that require it.
/// </summary>
public sealed class HandleNonStandardFrontchannelErrorResponse : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireRedirectionRequest>()
.UseSingletonHandler<HandleNonStandardFrontchannelErrorResponse>()
.SetOrder(HandleFrontchannelErrorResponse.Descriptor.Order - 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Note: some providers are known to return non-standard errors.
// To normalize the set of errors handled by the OpenIddict client,
// the non-standard errors are mapped to their standard equivalent.
//
// Errors that are not handled here will be automatically handled
// by the standard handler present in the core OpenIddict client.
if (context.Registration.ProviderType is ProviderTypes.Bitly &&
(bool?) context.Request["invalid"] is true)
{
// Note: Bitly uses custom "invalid" and "reason" parameters instead of
// the standard "error" parameter defined by the OAuth 2.0 specification.
var error = (string?) context.Request["reason"];
context.Reject(
error: error switch
{
"deny" => Errors.AccessDenied,
_ => Errors.ServerError
},
description: error switch
{
"deny" => SR.GetResourceString(SR.ID2149),
_ => SR.GetResourceString(SR.ID2152)
},
uri: error switch
{
"deny" => SR.FormatID8000(SR.ID2149),
_ => SR.FormatID8000(SR.ID2152)
});
return ValueTask.CompletedTask;
}
else if (context.Registration.ProviderType is ProviderTypes.Deezer)
{
// Note: Deezer uses a custom "error_reason" parameter instead of the
// standard "error" parameter defined by the OAuth 2.0 specification.
//
// See https://developers.deezer.com/api/oauth for more information.
var error = (string?) context.Request["error_reason"];
if (!string.IsNullOrEmpty(error))
{
context.Reject(
error: error switch
{
"user_denied" => Errors.AccessDenied,
_ => Errors.ServerError
},
description: error switch
{
"user_denied" => SR.GetResourceString(SR.ID2149),
_ => SR.GetResourceString(SR.ID2152)
},
uri: error switch
{
"user_denied" => SR.FormatID8000(SR.ID2149),
_ => SR.FormatID8000(SR.ID2152)
});
return ValueTask.CompletedTask;
}
}
else if (context.Registration.ProviderType is ProviderTypes.Huawei)
{
var error = (long?) context.Request[Parameters.Error];
if (error is not null)
{
context.Reject(
error: error switch
{
1107 => Errors.AccessDenied,
_ => Errors.ServerError
},
description: error switch
{
1107 => SR.GetResourceString(SR.ID2149),
_ => SR.GetResourceString(SR.ID2152)
},
uri: error switch
{
1107 => SR.FormatID8000(SR.ID2149),
_ => SR.FormatID8000(SR.ID2152)
});
return ValueTask.CompletedTask;
}
}
else if (context.Registration.ProviderType is ProviderTypes.LinkedIn)
{
var error = (string?) context.Request[Parameters.Error];
if (string.Equals(error, "user_cancelled_authorize", StringComparison.Ordinal) ||
string.Equals(error, "user_cancelled_login", StringComparison.Ordinal))
{
context.Reject(
error: Errors.AccessDenied,
description: SR.GetResourceString(SR.ID2149),
uri: SR.FormatID8000(SR.ID2149));
return ValueTask.CompletedTask;
}
}
else if (context.Registration.ProviderType is ProviderTypes.Mixcloud or ProviderTypes.Pipedrive)
{
var error = (string?) context.Request[Parameters.Error];
if (string.Equals(error, "user_denied", StringComparison.Ordinal))
{
context.Reject(
error: Errors.AccessDenied,
description: SR.GetResourceString(SR.ID2149),
uri: SR.FormatID8000(SR.ID2149));
return ValueTask.CompletedTask;
}
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for validating custom parameters for the providers that require it.
/// </summary>
public sealed class ValidateNonStandardParameters : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireRedirectionRequest>()
.AddFilter<RequireStateTokenPrincipal>()
.AddFilter<RequireStateTokenValidated>()
.UseSingletonHandler<ValidateNonStandardParameters>()
.SetOrder(ResolveGrantTypeAndResponseTypeFromStateToken.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
if (context.Registration.ProviderType is ProviderTypes.Shopify)
{
var domain = (string?) context.Request["shop"];
if (string.IsNullOrEmpty(domain))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2029("shop"),
uri: SR.FormatID8000(SR.ID2029));
return ValueTask.CompletedTask;
}
// Resolve the shop name from the authentication properties.
if (!context.Properties.TryGetValue(Shopify.Properties.ShopName, out string? name) ||
string.IsNullOrEmpty(name))
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0412));
}
// Note: the shop domain extracted from the redirection request is not used by OpenIddict (that stores
// the shop name in the state token), but it can be resolved and used by the developers in their own code.
//
// To ensure the value is correct, it is compared to the shop name stored in the state token: if
// the two don't match, the request is automatically rejected to prevent a potential mixup attack.
if (!string.Equals(domain, $"{name}.myshopify.com", StringComparison.Ordinal))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2052("shop"),
uri: SR.FormatID8000(SR.ID2052));
return ValueTask.CompletedTask;
}
}
// VK ID uses a non-standard "device_id" parameter in authorization responses.
else if (context.Registration.ProviderType is ProviderTypes.VkId)
{
var identifier = (string?) context.Request["device_id"];
if (string.IsNullOrEmpty(identifier))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2029("device_id"),
uri: SR.FormatID8000(SR.ID2029));
return ValueTask.CompletedTask;
}
// Store the device identifier as an authentication property
// so it can be resolved later to make refresh token requests.
context.Properties[VkId.Properties.DeviceId] = identifier;
}
// Zoho returns the region of the authenticated user as a non-standard "location" parameter
// that must be used to compute the address of the token and userinfo endpoints.
else if (context.Registration.ProviderType is ProviderTypes.Zoho)
{
var location = (string?) context.Request["location"];
if (string.IsNullOrEmpty(location))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2029("location"),
uri: SR.FormatID8000(SR.ID2029));
return ValueTask.CompletedTask;
}
// Ensure the specified location corresponds to well-known region.
if (location.ToUpperInvariant() is not ("AU" or "CA" or "EU" or "IN" or "JP" or "SA" or "UK" or "US"))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2052("location"),
uri: SR.FormatID8000(SR.ID2052));
return ValueTask.CompletedTask;
}
// Store the validated location as an authentication property
// so it can be resolved later to determine the user region.
context.Properties[Zoho.Properties.Location] = location;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for overriding the negotiated token
/// endpoint client authentication method for the providers that require it.
/// </summary>
public sealed class OverrideTokenEndpointClientAuthenticationMethod : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireTokenRequest>()
.UseSingletonHandler<OverrideTokenEndpointClientAuthenticationMethod>()
.SetOrder(AttachTokenEndpointClientAuthenticationMethod.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
context.TokenEndpointClientAuthenticationMethod = context.Registration.ProviderType switch
{
// Note: Bitly only supports using "client_secret_post" for the authorization code
// grant but not for the resource owner password credentials grant, that requires
// using the "client_secret_basic" method instead.
ProviderTypes.Bitly when context.GrantType is GrantTypes.Password
=> ClientAuthenticationMethods.ClientSecretBasic,
// Note: Reddit requires using basic authentication to flow the client_id for all types
// of client applications, even when there's no client_secret assigned or attached.
ProviderTypes.Reddit => ClientAuthenticationMethods.ClientSecretBasic,
_ => context.TokenEndpointClientAuthenticationMethod
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for overriding the address
/// of the token endpoint for the providers that require it.
/// </summary>
public sealed class OverrideTokenEndpoint : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.UseSingletonHandler<OverrideTokenEndpoint>()
.SetOrder(ResolveTokenEndpoint.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
context.TokenEndpoint = context.Registration.ProviderType switch
{
// Shopify is a multitenant provider that requires setting the token endpoint dynamically
// based on the shop name stored in the authentication properties set during the challenge.
//
// For more information, see
// https://shopify.dev/docs/apps/auth/oauth/getting-started#step-5-get-an-access-token.
ProviderTypes.Shopify when context.GrantType is GrantTypes.AuthorizationCode &&
context.Properties[Shopify.Properties.ShopName] is var name =>
new Uri($"https://{name}.myshopify.com/admin/oauth/access_token", UriKind.Absolute),
// Trovo uses a different token endpoint for the refresh token grant.
//
// For more information, see
// https://developer.trovo.live/docs/APIs.html#_4-3-refresh-access-token.
ProviderTypes.Trovo when context.GrantType is GrantTypes.RefreshToken
=> new Uri("https://open-api.trovo.live/openplatform/refreshtoken", UriKind.Absolute),
// Zoho requires using a region-specific token endpoint determined using
// the "location" parameter returned from the authorization endpoint.
//
// For more information, see
// https://www.zoho.com/accounts/protocol/oauth/multi-dc/client-authorization.html.
ProviderTypes.Zoho when context.GrantType is GrantTypes.AuthorizationCode
=> ((string?) context.Request["location"])?.ToUpperInvariant() switch
{
"AU" => new Uri("https://accounts.zoho.com.au/oauth/v2/token", UriKind.Absolute),
"CA" => new Uri("https://accounts.zohocloud.ca/oauth/v2/token", UriKind.Absolute),
"EU" => new Uri("https://accounts.zoho.eu/oauth/v2/token", UriKind.Absolute),
"IN" => new Uri("https://accounts.zoho.in/oauth/v2/token", UriKind.Absolute),
"JP" => new Uri("https://accounts.zoho.jp/oauth/v2/token", UriKind.Absolute),
"SA" => new Uri("https://accounts.zoho.sa/oauth/v2/token", UriKind.Absolute),
"UK" => new Uri("https://accounts.zoho.uk/oauth/v2/token", UriKind.Absolute),
"US" => new Uri("https://accounts.zoho.com/oauth/v2/token", UriKind.Absolute),
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0477))
},
ProviderTypes.Zoho when context.GrantType is GrantTypes.RefreshToken
=> !context.Properties.TryGetValue(Zoho.Properties.Location, out string? location) ||
string.IsNullOrEmpty(location) ? throw new InvalidOperationException(SR.GetResourceString(SR.ID0451)) :
location?.ToUpperInvariant() switch
{
"AU" => new Uri("https://accounts.zoho.com.au/oauth/v2/token", UriKind.Absolute),
"CA" => new Uri("https://accounts.zohocloud.ca/oauth/v2/token", UriKind.Absolute),
"EU" => new Uri("https://accounts.zoho.eu/oauth/v2/token", UriKind.Absolute),
"IN" => new Uri("https://accounts.zoho.in/oauth/v2/token", UriKind.Absolute),
"JP" => new Uri("https://accounts.zoho.jp/oauth/v2/token", UriKind.Absolute),
"SA" => new Uri("https://accounts.zoho.sa/oauth/v2/token", UriKind.Absolute),
"UK" => new Uri("https://accounts.zoho.uk/oauth/v2/token", UriKind.Absolute),
"US" => new Uri("https://accounts.zoho.com/oauth/v2/token", UriKind.Absolute),
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0477))
},
_ => context.TokenEndpoint
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for adding non-standard claims to the client
/// assertions used for the token endpoint for the providers that require it.
/// </summary>
public sealed class AttachNonStandardClientAssertionClaims : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireClientAssertionGenerated>()
.UseSingletonHandler<AttachNonStandardClientAssertionClaims>()
.SetOrder(PrepareClientAssertionPrincipal.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(context.ClientAssertionPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// For client assertions to be considered valid by the Apple ID authentication service,
// the team identifier associated with the developer account MUST be used as the issuer
// and the static "https://appleid.apple.com" URL MUST be used as the token audience.
//
// For more information about the custom client authentication method implemented by Apple,
// see https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens.
if (context.Registration.ProviderType is ProviderTypes.Apple)
{
var settings = context.Registration.GetAppleSettings();
context.ClientAssertionPrincipal.SetClaim(Claims.Private.Issuer, settings.TeamId);
context.ClientAssertionPrincipal.SetAudiences("https://appleid.apple.com");
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for overriding the scopes for the providers that require it.
/// </summary>
public sealed class OverrideScopes : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireTokenRequest>()
.UseSingletonHandler<OverrideScopes>()
.SetOrder(AttachTokenRequestParameters.Descriptor.Order - 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc />
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
// osu! requires at least one scope to be set for client credentials grant, as tokens without
// scopes are not valid. If no scope is explicitly specified, use the default value "public".
if (context.GrantType is GrantTypes.ClientCredentials &&
context.Registration.ProviderType is ProviderTypes.Osu &&
context.Scopes.Count is 0)
{
context.Scopes.Add("public");
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for attaching additional parameters
/// to the token request for the providers that require it.
/// </summary>
public sealed class AttachAdditionalTokenRequestParameters : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireTokenRequest>()
.UseSingletonHandler<AttachAdditionalTokenRequestParameters>()
.SetOrder(AttachTokenRequestParameters.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(context.TokenRequest is not null, SR.GetResourceString(SR.ID4008));
// When using the device authorization code grant, Amazon requires sending a non-standard
// "user_code" node containing the user code returned by the device authorization endpoint.
//
// As the user code is not a standard concept for token requests, the user code is expected
// to be attached as an Amazon-specific authentication property. If no user code or an empty
// value was attached, an exception is thrown to abort the authentication process.
if (context.GrantType is GrantTypes.DeviceCode &&
context.Registration.ProviderType is ProviderTypes.Amazon)
{
if (!context.Properties.TryGetValue(Amazon.Properties.UserCode, out string? code) ||
string.IsNullOrEmpty(code))
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0427));
}
context.TokenRequest.UserCode = code;
}
// VK ID requires attaching a non-standard "device_id" parameter to all token requests.
//
// This parameter is either resolved from the authorization response (for the authorization
// code or hybrid grants) or manually provided by the application for other grant types.
else if (context.Registration.ProviderType is ProviderTypes.VkId)
{
context.TokenRequest["device_id"] = context.GrantType switch
{
GrantTypes.AuthorizationCode or GrantTypes.Implicit => context.Request["device_id"],
_ when context.Properties.TryGetValue(VkId.Properties.DeviceId, out string? identifier) &&
!string.IsNullOrEmpty(identifier) => identifier,
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0467))
};
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for attaching custom client credentials
/// parameters to the token request for the providers that require it.
/// </summary>
public sealed class AttachTokenRequestNonStandardClientCredentials : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireTokenRequest>()
.UseSingletonHandler<AttachTokenRequestNonStandardClientCredentials>()
.SetOrder(AttachTokenRequestClientCredentials.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(context.TokenRequest is not null, SR.GetResourceString(SR.ID4008));
// Apple implements a non-standard client authentication method for its endpoints that
// is inspired by the standard private_key_jwt method but doesn't use the standard
// client_assertion/client_assertion_type parameters. Instead, the client assertion
// must be sent as a "dynamic" client secret using client_secret_post. Since the logic
// is the same as private_key_jwt, the configuration is amended to assume Apple supports
// private_key_jwt and an event handler is responsible for populating the client_secret
// parameter using the client assertion once it has been generated by OpenIddict.
if (context.Registration.ProviderType is ProviderTypes.Apple)
{
context.TokenRequest.ClientSecret = context.TokenRequest.ClientAssertion;
context.TokenRequest.ClientAssertion = null;
context.TokenRequest.ClientAssertionType = null;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for overriding the redirect_uri
/// attached to the token request for the providers that require it.
/// </summary>
public sealed class AdjustRedirectUriInTokenRequest : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireTokenRequest>()
.UseSingletonHandler<AdjustRedirectUriInTokenRequest>()
.SetOrder(AttachTokenRequestClientCredentials.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(context.TokenRequest is not null, SR.GetResourceString(SR.ID4008));
if (context.TokenRequest.RedirectUri is null)
{
return ValueTask.CompletedTask;
}
// Note: some providers don't support the "state" parameter, don't flow
// it correctly or don't include it in errored authorization responses.
//
// Since OpenIddict requires flowing the state token in every circumstance
// (for security reasons), the state token is appended to the "redirect_uri"
// instead of being sent as a standard OAuth 2.0 authorization request parameter.
//
// Note: for token requests to use the actual redirect_uri that was sent as part
// of the authorization requests, the value persisted in the state token principal
// MUST be replaced to include the state token received by the redirection endpoint.
context.TokenRequest.RedirectUri = context.Registration.ProviderType switch
{
ProviderTypes.Deezer or
ProviderTypes.Huawei or
ProviderTypes.Mixcloud => OpenIddictHelpers.AddQueryStringParameter(
uri : new Uri(context.TokenRequest.RedirectUri, UriKind.Absolute),
name : Parameters.State,
value: context.StateToken).AbsoluteUri,
_ => context.TokenRequest.RedirectUri
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for overriding the set
/// of required tokens for the providers that require it.
/// </summary>
public sealed class OverrideValidatedBackchannelTokens : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.UseSingletonHandler<OverrideValidatedBackchannelTokens>()
.SetOrder(EvaluateValidatedBackchannelTokens.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
(context.ExtractBackchannelIdentityToken,
context.RequireBackchannelIdentityToken,
context.ValidateBackchannelIdentityToken) = context.Registration.ProviderType switch
{
// Clever claims the OpenID Connect flavor of the code flow is supported but
// their implementation doesn't always return an id_token from the token endpoint.
ProviderTypes.Clever => (true, false, true),
// While PayPal claims the OpenID Connect flavor of the code flow is supported,
// their implementation doesn't return an id_token from the token endpoint.
ProviderTypes.PayPal => (false, false, false),
// NetSuite does not return an id_token when using the refresh_token grant type.
//
// Additionally, the at_hash inside the id_token is not a valid hash of the access
// token, but is instead a copy of the RS256 signature within the access token.
ProviderTypes.NetSuite => (true, false, false),
_ => (context.ExtractBackchannelIdentityToken,
context.RequireBackchannelIdentityToken,
context.ValidateBackchannelIdentityToken)
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for disabling the backchannel
/// identity token nonce validation for the providers that require it.
/// </summary>
public sealed class DisableBackchannelIdentityTokenNonceValidation : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.UseSingletonHandler<DisableBackchannelIdentityTokenNonceValidation>()
.SetOrder(ValidateBackchannelIdentityTokenNonce.Descriptor.Order - 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Note: despite implementing OpenID Connect, some providers are known to implement the
// specification incorrectly and either don't support the "nonce" authorization request
// parameter, don't include it in the issued identity tokens or flow an unexpected value.
//
// Despite being an important security feature, nonce validation is explicitly disabled
// for the providers that are known to cause errors when nonce validation is enforced.
context.DisableBackchannelIdentityTokenNonceValidation = context.Registration.ProviderType switch
{
// These providers don't include the nonce in their identity tokens:
ProviderTypes.Asana or ProviderTypes.DocuSign or
ProviderTypes.Dropbox or ProviderTypes.FaceIt or
ProviderTypes.LinkedIn or ProviderTypes.QuickBooksOnline or
ProviderTypes.WorldId => true,
_ => context.DisableBackchannelIdentityTokenNonceValidation
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for overriding the userinfo retrieval for the providers that require it.
/// </summary>
public sealed class OverrideUserInfoRetrieval : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.UseSingletonHandler<OverrideUserInfoRetrieval>()
.SetOrder(EvaluateUserInfoRequest.Descriptor.Order + 250)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
context.SendUserInfoRequest = context.Registration.ProviderType switch
{
// Note: ADFS has severe restrictions affecting the ability to access the userinfo endpoint
// (e.g the "resource" parameter MUST be null or the "urn:microsoft:userinfo" value MUST be
// used, which prevents specifying any other resource as only one value is allowed by ADFS).
//
// Since the userinfo endpoint returns very limited information anyway,
// userinfo retrieval is always disabled for the ADFS provider.
ProviderTypes.ActiveDirectoryFederationServices => false,
// Note: these providers don't have a static userinfo endpoint attached to their configuration
// so OpenIddict doesn't, by default, send a userinfo request. Since a dynamic endpoint is later
// computed and attached to the context, the default value MUST be overridden to send a request.
ProviderTypes.Dailymotion or ProviderTypes.HubSpot or ProviderTypes.Osu or
ProviderTypes.SuperOffice or ProviderTypes.Zoho
when context.GrantType is GrantTypes.AuthorizationCode or GrantTypes.DeviceCode or
GrantTypes.Implicit or GrantTypes.Password or
GrantTypes.RefreshToken or
// Apply the same logic for custom grant types.
(not null and not (GrantTypes.AuthorizationCode or GrantTypes.ClientCredentials or
GrantTypes.DeviceCode or GrantTypes.Implicit or
GrantTypes.Password or GrantTypes.RefreshToken)) &&
!context.DisableUserInfoRetrieval && (!string.IsNullOrEmpty(context.BackchannelAccessToken) ||
!string.IsNullOrEmpty(context.FrontchannelAccessToken)) => true,
// Note: the frontchannel or backchannel access tokens returned by Microsoft Entra ID
// when a Xbox scope is requested cannot be used with the userinfo endpoint as they use
// a legacy format that is not supported by the Microsoft Entra ID userinfo implementation.
//
// To work around this limitation, userinfo retrieval is disabled when a Xbox scope is requested.
ProviderTypes.Microsoft => context.GrantType switch
{
GrantTypes.AuthorizationCode or GrantTypes.Implicit when
context.StateTokenPrincipal is ClaimsPrincipal principal &&
principal.HasClaim(static claim =>
claim.Type is Claims.Private.Scope &&
claim.Value.StartsWith("XboxLive.", StringComparison.OrdinalIgnoreCase))
=> false,
GrantTypes.DeviceCode or GrantTypes.RefreshToken when
context.Scopes.Any(static scope => scope.StartsWith("XboxLive.", StringComparison.OrdinalIgnoreCase))
=> false,
_ => context.SendUserInfoRequest
},
// Note: some providers don't allow querying the userinfo endpoint when the "openid" scope
// is not requested or granted. To work around that, userinfo is disabled when the "openid"