openid-client 1.0.0-alpha.7

OpenID client for Rust
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
use std::{collections::HashMap, str::FromStr};

use serde_json::Value;
use url::Url;

use crate::{
    client_utils::{
        authorization_code::{
            self, validate_access_token_response, validate_auth_code_oauth_response,
            validate_auth_code_openid_response, validate_auth_response, validate_hybrid_response,
            validate_implicit_response,
        },
        jwt::{validate_jwt, JwtValidationParameters},
    },
    config::{ClientAuth, DPoPOptions, OpenIdClientConfiguration},
    errors::{OidcReturn, OpenIdError},
    helpers::{
        base64_url_encode, deserialize, generate_random, unix_timestamp, url_decode,
        webfinger_normalize,
    },
    http::Http,
    jwk::{Jwk, JwksResponse},
    token_set::TokenSet,
    types::{
        http_client::{HttpMethod, HttpRequest, HttpResponse, OidcHttpClient, RequestBody},
        AuthMethods, AuthenticatedEndpoints, AuthorizationCodeGrantParameters,
        AuthorizationCodeGrantValidationParameters, AuthorizationParameters, CibaAuthRequest,
        CibaAuthResponse, ClientRegistrationRequest, ClientRegistrationResponse,
        DeviceAuthorizationRequest, DeviceAuthorizationResponse, EndSessionParameters, Header,
        ImplicitGrantParameters, IssuerMetadata, NonceCheck, OpenIdCrypto, OpenIdResponseType,
        Payload, PushedAuthorizationResponse, UserinfoTokenLocation, WebFingerResponse,
    },
};

/// # Client
/// Represents the Client
pub struct Client;

impl Client {
    /// # Discover OIDC Issuer
    ///
    /// Discover an OIDC Issuer using the issuer url.
    ///
    /// - `issuer` - The issuer url (absolute).
    /// - `http_client` - The http client used to make the request.
    pub async fn discover_oidc_async<T: OidcHttpClient>(
        issuer: &str,
        http_client: &T,
    ) -> OidcReturn<IssuerMetadata> {
        let mut request = HttpRequest::new();

        let base_url =
            Url::parse(issuer).map_err(|_| OpenIdError::new_error("Invalid Issuer Url"))?;

        let well_known_path = format!(
            "{}/.well-known/openid-configuration",
            base_url.path().trim_end_matches('/')
        );
        request.url = base_url;
        request.url.set_path(&well_known_path);

        let res = Http::default()
            .request_async(request, http_client, None)
            .await?;

        if let Some(body) = res.body {
            return match deserialize::<IssuerMetadata>(&body) {
                Ok(metadata) => {
                    let expected = issuer.trim_end_matches('/');
                    let actual = metadata.issuer.trim_end_matches('/');
                    if actual != expected {
                        return Err(OpenIdError::new_error(format!(
                            "discovered issuer mismatch, expected {}, got: {}",
                            issuer, metadata.issuer
                        )));
                    }
                    Ok(metadata)
                }
                Err(e) => Err(OpenIdError::new_error(format!(
                    "Error while parsing issuer metadata: {:?}",
                    e
                ))),
            };
        }

        Err(OpenIdError::new_error("Response does not have a body"))
    }

    /// # Discover OAuth Issuer
    ///
    /// Discover an OAuth Issuer using the issuer url.
    ///
    /// - `issuer` - The issuer url (absolute).
    /// - `http_client` - The http client used to make the request.
    pub async fn discover_oauth_async<T: OidcHttpClient>(
        issuer: &str,
        http_client: &T,
    ) -> OidcReturn<IssuerMetadata> {
        let mut request = HttpRequest::new();

        let base_url =
            Url::parse(issuer).map_err(|_| OpenIdError::new_error("Invalid Issuer Url"))?;

        let well_known_path = format!(
            "{}/.well-known/oauth-authorization-server",
            base_url.path().trim_end_matches('/')
        );
        request.url = base_url;
        request.url.set_path(&well_known_path);

        let res = Http::default()
            .request_async(request, http_client, None)
            .await?;

        if let Some(body) = res.body {
            return match deserialize::<IssuerMetadata>(&body) {
                Ok(metadata) => {
                    let expected = issuer.trim_end_matches('/');
                    let actual = metadata.issuer.trim_end_matches('/');
                    if actual != expected {
                        return Err(OpenIdError::new_error(format!(
                            "discovered issuer mismatch, expected {}, got: {}",
                            issuer, metadata.issuer
                        )));
                    }
                    Ok(metadata)
                }
                Err(_) => Err(OpenIdError::new_error(
                    "invalid_authorization_server_metadata".to_string(),
                )),
            };
        }

        Err(OpenIdError::new_error("Response does not have a body"))
    }

    /// # Fetch Issuer Jwks
    ///
    /// Fetches Issuer Json Web Key Set from `jwks_uri`.
    ///
    /// - `issuer` - The issuer metadata.
    /// - `http_client` - The http client to make the request.
    pub async fn fetch_issuer_jwks_async<H: OidcHttpClient>(
        issuer: &IssuerMetadata,
        http_client: &H,
    ) -> OidcReturn<Vec<Jwk>> {
        match &issuer.jwks_uri {
            Some(jwks_uri) => {
                let request = HttpRequest::new()
                    .url(Url::parse(jwks_uri).map_err(|e| OpenIdError::new_error(e.to_string()))?)
                    .expect_json()
                    .method(HttpMethod::GET)
                    .expect_status_code(200);

                let response = Http::default()
                    .request_async(request, http_client, None)
                    .await?;

                match response.body {
                    Some(raw_body) => {
                        let jwks_response = deserialize::<JwksResponse>(&raw_body)
                            .map_err(OpenIdError::new_error)?;
                        Ok(jwks_response.keys)
                    }
                    None => Err(OpenIdError::new_error("JWKS response empty")),
                }
            }
            None => Err(OpenIdError::new_error(
                "jwks_uri not found in the issuer metadata",
            )),
        }
    }

    /// # WebFinger OIDC Issuer Discovery
    ///
    /// Discover an OIDC Issuer using the user email, url, url with port syntax or acct syntax.
    ///
    /// - `resource` - The resource.
    /// - `http_client` - The http client to make the request.
    pub async fn webfinger_async<T: OidcHttpClient>(
        resource: &str,
        http_client: &T,
    ) -> OidcReturn<IssuerMetadata> {
        let resource = webfinger_normalize(resource);

        let mut host: Option<String> = None;

        if resource.starts_with("acct:") {
            let split: Vec<&str> = resource.split('@').collect();
            host = split.last().map(|s| s.to_string());
        } else if resource.starts_with("https://") {
            let url =
                Url::from_str(&resource).map_err(|e| OpenIdError::new_error(e.to_string()))?;

            if let Some(host_str) = url.host_str() {
                host = match url.port() {
                    Some(port) => Some(host_str.to_string() + &format!(":{port}")),
                    None => Some(host_str.to_string()),
                }
            }
        }

        if host.is_none() {
            return Err(OpenIdError::new_error("given input was invalid"));
        }

        let mut web_finger_url =
            Url::parse(&format!("https://{}/.well-known/webfinger", host.unwrap())).unwrap();

        let mut headers = HashMap::new();
        headers.insert("accept".to_string(), vec!["application/json".to_string()]);

        web_finger_url.set_query(Some(&format!(
            "resource={}&rel=http%3A%2F%2Fopenid.net%2Fspecs%2Fconnect%2F1.0%2Fissuer",
            urlencoding::encode(&resource)
        )));

        let request = HttpRequest::new()
            .url(web_finger_url)
            .method(HttpMethod::GET)
            .headers(headers);

        let response = Http::default()
            .request_async(request, http_client, None)
            .await?;

        let body = response
            .body
            .as_ref()
            .ok_or_else(|| OpenIdError::new_error("webfinger response body is empty"))?;

        let webfinger_response = match deserialize::<WebFingerResponse>(body) {
            Ok(res) => res,
            Err(_) => {
                return Err(OpenIdError::new_error(
                    "invalid_webfinger_response".to_string(),
                ));
            }
        };

        let location_link_result = webfinger_response
            .links
            .iter()
            .find(|x| x.rel == "http://openid.net/specs/connect/1.0/issuer" && x.href.is_some());

        let expected_issuer = match location_link_result.and_then(|l| l.href.as_ref()) {
            Some(iss) => iss,
            _ => {
                return Err(OpenIdError::new_error(
                    "No issuer found in webfinger response",
                ));
            }
        };

        if !expected_issuer.starts_with("https://") {
            return Err(OpenIdError::new_error(format!(
                "invalid issuer location {expected_issuer}"
            )));
        }

        let issuer_metadata = Client::discover_oidc_async(expected_issuer, http_client).await?;

        if &issuer_metadata.issuer != expected_issuer {
            return Err(OpenIdError::new_error(format!(
                "discovered issuer mismatch, expected {expected_issuer}, got: {}",
                issuer_metadata.issuer
            )));
        }

        Ok(issuer_metadata)
    }

    /// # Authorization Url
    /// Builds an authorization url with respect to the `authorization_parameters`.
    ///
    /// - `config` - Openid client configuration.
    /// - `authorization_parameters` - [AuthorizationParameters]: Customize the authorization request.
    pub fn authorization_url(
        config: &OpenIdClientConfiguration,
        mut authorization_parameters: AuthorizationParameters,
    ) -> OidcReturn<String> {
        let mut authorization_endpoint = config.authorization_endpoint()?;

        if authorization_parameters.client_id.is_none() {
            authorization_parameters.client_id = Some(config.client.client_id.to_owned());
        }

        let authorization_parameters_map: HashMap<String, String> = authorization_parameters.into();

        authorization_endpoint
            .query_pairs_mut()
            .extend_pairs(authorization_parameters_map);

        Ok(authorization_endpoint.to_string())
    }

    /// # End Session Url
    /// Builds an endsession url with respect to the `end_session_parameters`.
    ///
    /// - `config` - Openid client configuration.
    /// - `end_session_parameters` - [EndSessionParameters]: Customize the endsession url.
    pub fn endsession_url(
        config: &OpenIdClientConfiguration,
        mut end_session_parameters: EndSessionParameters,
    ) -> OidcReturn<String> {
        let mut end_session_endpoint = config.end_session_endpoint()?;

        if end_session_parameters.client_id.is_none() {
            end_session_parameters.client_id = Some(config.client.client_id.to_owned());
        }

        {
            let mut query_params = end_session_endpoint.query_pairs_mut();

            if let Some(client_id) = end_session_parameters.client_id {
                query_params.append_pair("client_id", &client_id);
            }

            if let Some(post_logout_redirect_uri) = end_session_parameters
                .post_logout_redirect_uri
                .or_else(|| config.client.post_logout_redirect_uri.clone())
            {
                query_params.append_pair("post_logout_redirect_uri", &post_logout_redirect_uri);
            }

            if let Some(state) = end_session_parameters.state {
                query_params.append_pair("state", &state);
            }

            if let Some(id_token_hint) = end_session_parameters.id_token_hint {
                query_params.append_pair("id_token_hint", &id_token_hint);
            }

            if let Some(logout_hint) = end_session_parameters.logout_hint {
                query_params.append_pair("logout_hint", &logout_hint);
            }
        }

        Ok(end_session_endpoint.to_string())
    }

    /// # Authorization Post
    /// Builds an authorization post page with respect to the `authorization_parameters`.
    ///
    /// - `config` - Openid client configuration.
    /// - `authorization_parameters` - [AuthorizationParameters]: Customize the authorization request.
    pub fn authorization_post(
        config: &OpenIdClientConfiguration,
        mut authorization_parameters: AuthorizationParameters,
    ) -> OidcReturn<String> {
        let authorization_endpoint = config.authorization_endpoint()?;

        if authorization_parameters.client_id.is_none() {
            authorization_parameters.client_id = Some(config.client.client_id.to_owned());
        }

        let authorization_parameters_map: HashMap<String, String> = authorization_parameters.into();

        let mut html = r#"<!DOCTYPE html>
        <head>
        <title>Requesting Authorization</title>
        </head>
        <body onload="javascript:document.forms[0].submit()">
        <form method="post" action=""#
            .to_string()
            + authorization_endpoint.as_ref()
            + r#"">"#
            + "\n";

        for (param, value) in authorization_parameters_map {
            let escaped_param = html_escape(&param);
            let escaped_value = html_escape(&value);
            html = html
                + r#"<input type="hidden" name=""#
                + &escaped_param
                + r#"" value=""#
                + &escaped_value
                + r#""/>"#
                + "\n";
        }

        html += r#"</form>
        </body>
        </html>"#;

        Ok(html)
    }

    /// # Token Grant
    /// Performs a grant at the token endpoint.
    ///
    /// - `config` - Openid client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `body` - Grant request body.
    /// - `http_client` - The http client to make the request.
    /// - `dpop_options` - Optional DPoP options for the request.
    pub async fn grant_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        body: RequestBody,
        http_client: &H,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<TokenSet> {
        if !matches!(body, RequestBody::Form(_)) {
            return Err(OpenIdError::new_error(
                "grant_async() only supports form url encoded body",
            ));
        }

        let response = authenticated_post_async(
            config,
            crypto,
            AuthenticatedEndpoints::Token,
            body,
            http_client,
            dpop_options,
        )
        .await?;

        let body = response
            .body
            .ok_or(OpenIdError::new_error("body expected in grant response"))?;

        deserialize::<TokenSet>(&body).or(Err(OpenIdError::new_error(
            "could not convert body to TokenSet",
        )))
    }

    /// # Authorization Code Grant
    ///
    /// Performs authorization code grant on the token endpoint.
    ///
    /// > This method does not validate the tokens returned. Call [Client::validate_authorization_code_grant_async]
    /// > for validating the tokens.
    ///
    /// - `config` - Openid client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `http_client` - The http client to make the request.
    /// - `callback_request` - The callback request received from the provider.
    /// - `parameters` - [AuthorizationCodeGrantParameters]: Parameters for the authorization code grant.
    /// - `dpop_options` - Optional DPoP options for the request.
    pub async fn authorization_code_grant_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        http_client: &H,
        callback_request: HttpRequest,
        parameters: AuthorizationCodeGrantParameters,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<TokenSet> {
        let callback_params = match callback_request.method {
            HttpMethod::GET => match config.response_type {
                OpenIdResponseType::Hybrid => {
                    let fragment = callback_request
                        .url
                        .fragment()
                        .ok_or(OpenIdError::new_error("fragment not found"))?;
                    url_decode(fragment)
                }
                OpenIdResponseType::Implicit => {
                    return Err(OpenIdError::new_error("unsupported response type"))
                }
                // Support fragment.jwt?
                OpenIdResponseType::Jarm | OpenIdResponseType::Code => callback_request
                    .url
                    .query_pairs()
                    .map(|(k, v)| (k.into_owned(), v.into_owned()))
                    .collect(),
            },
            HttpMethod::POST => match callback_request.body {
                Some(RequestBody::Form(body)) => body,
                _ => return Err(OpenIdError::new_error("Body not found/incorrect format")),
            },
            _ => return Err(OpenIdError::new_error("unexpected Request HTTP method")),
        };

        let callback_params = match config.response_type {
            OpenIdResponseType::Jarm => authorization_code::validate_jarm(
                config,
                crypto,
                callback_params,
                parameters.state_check,
            )?,
            OpenIdResponseType::Hybrid => validate_hybrid_response(
                config,
                crypto,
                callback_params,
                parameters.state_check,
                parameters.nonce_check.clone(),
                parameters.max_age_check.clone(),
            )?,
            OpenIdResponseType::Implicit => {
                return Err(OpenIdError::new_error("unsupported response type"))
            }
            OpenIdResponseType::Code => authorization_code::validate_auth_response(
                &config.issuer.issuer,
                config
                    .issuer
                    .authorization_response_iss_parameter_supported
                    .is_some_and(|s| s),
                callback_params,
                parameters.state_check,
            )?,
        };

        let code = callback_params.get("code").ok_or(OpenIdError::new_error(
            "no authorization code in \"callback_params\"",
        ))?;

        if code.is_empty() {
            return Err(OpenIdError::new_error(
                "authorization code in \"callback_params\" is empty",
            ));
        }

        let mut token_request_params = HashMap::new();
        token_request_params.extend(parameters.additional_parameters);
        token_request_params.insert("grant_type".to_owned(), "authorization_code".to_owned());
        token_request_params.insert("code".to_owned(), code.to_owned());
        token_request_params.insert("redirect_uri".to_owned(), parameters.redirect_uri);
        if let Some(code_verifier) = parameters.pkce_code_verifier {
            token_request_params.insert("code_verifier".to_owned(), code_verifier);
        }

        Client::grant_async(
            config,
            crypto,
            RequestBody::Form(token_request_params),
            http_client,
            dpop_options,
        )
        .await
    }

    /// # Validate Authorization Code Grant
    ///
    /// Validates tokens obtained from authorization code grant.
    ///
    /// - `config` - Openid client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `token_set` - The token set returned by the authorization code grant.
    /// - `parameters` - [AuthorizationCodeGrantValidationParameters]: Parameters for validating the authorization code grant.
    pub async fn validate_authorization_code_grant_async<C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        token_set: TokenSet,
        parameters: AuthorizationCodeGrantValidationParameters,
    ) -> OidcReturn<TokenSet> {
        match (
            &parameters.nonce_check,
            &parameters.max_age_check,
            parameters.expect_id_token,
        ) {
            (Some(_), Some(_), _)
            | (Some(_), None, _)
            | (None, Some(_), _)
            | (None, None, true) => validate_auth_code_openid_response(
                config,
                crypto,
                token_set,
                parameters.nonce_check.unwrap_or(NonceCheck::ExpectNoNonce),
                parameters.max_age_check,
            ),
            (None, None, false) => validate_auth_code_oauth_response(config, crypto, token_set),
        }
    }

    /// # Implicit Code Grant
    ///
    /// Validates the returned access token and/or id token.
    ///
    /// - `config` - Openid client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `callback_request` - The callback request received from the provider.
    /// - `parameters` - [ImplicitGrantParameters]: Parameters for the implicit grant.
    pub async fn implicit_authentication_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        callback_request: HttpRequest,
        parameters: ImplicitGrantParameters,
    ) -> OidcReturn<TokenSet> {
        let mut callback_params = match callback_request.method {
            HttpMethod::GET => match config.response_type {
                OpenIdResponseType::Hybrid => {
                    return Err(OpenIdError::new_error("unsupported response type"))
                }
                OpenIdResponseType::Implicit => {
                    let fragment = callback_request
                        .url
                        .fragment()
                        .ok_or(OpenIdError::new_error("fragment not found"))?;
                    url_decode(fragment)
                }
                OpenIdResponseType::Jarm | OpenIdResponseType::Code => {
                    return Err(OpenIdError::new_error("unsupported response type"))
                }
            },
            HttpMethod::POST => match callback_request.body {
                Some(RequestBody::Form(body)) => body,
                _ => return Err(OpenIdError::new_error("Body not found/incorrect format")),
            },
            _ => return Err(OpenIdError::new_error("unexpected Request HTTP method")),
        };

        let id_token = callback_params.get("id_token").cloned();
        callback_params.remove("id_token");

        let access_token = callback_params.get("access_token").cloned();
        callback_params.remove("access_token");

        let callback_params = match config.response_type {
            OpenIdResponseType::Code | OpenIdResponseType::Jarm | OpenIdResponseType::Hybrid => {
                return Err(OpenIdError::new_error("unsupported response type"))
            }
            OpenIdResponseType::Implicit => validate_auth_response(
                &config.issuer.issuer,
                false,
                callback_params,
                parameters.state_check,
            )?,
        };

        let tokenset = TokenSet {
            access_token,
            id_token,
            expires_in: callback_params
                .get("expires_in")
                .and_then(|ei| ei.parse::<u64>().ok()),
            scope: callback_params.get("scope").cloned(),
            token_type: callback_params.get("token_type").cloned(),
            ..Default::default()
        };

        if parameters.expect_id_token && tokenset.id_token.is_none() {
            return Err(OpenIdError::new_error(
                "expected id_token in implicit response but none was returned",
            ));
        }

        let has_id_token = tokenset.id_token.is_some();

        validate_implicit_response(
            config,
            crypto,
            tokenset,
            has_id_token,
            parameters.nonce_check,
            parameters.max_age_check,
        )
    }

    /// # Refresh Token Grant
    ///
    /// Performs a refresh token grant.
    ///
    /// - `config` - Openid client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `http_client` - The http client to make the request.
    /// - `refresh_token` - The refresh token.
    /// - `additional_parameters` - Optional additional parameters for the grant.
    /// - `dpop_options` - Optional DPoP options for the request.
    pub async fn refresh_grant_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        http_client: &H,
        refresh_token: &str,
        additional_parameters: Option<HashMap<String, String>>,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<TokenSet> {
        let mut refresh_grant_params = HashMap::new();
        if let Some(additional_parameters) = additional_parameters {
            refresh_grant_params.extend(additional_parameters);
        }
        refresh_grant_params.insert("grant_type".to_owned(), "refresh_token".to_owned());
        refresh_grant_params.insert("refresh_token".to_owned(), refresh_token.to_owned());

        let tokenset = Client::grant_async(
            config,
            crypto,
            RequestBody::Form(refresh_grant_params),
            http_client,
            dpop_options,
        )
        .await?;

        validate_access_token_response(config, crypto, tokenset, &[], true)
    }

    /// # Pushed Authorization Request
    ///
    /// Performs a pushed authorization request.
    ///
    /// - `config` - Openid client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `http_client` - The http client to make the request.
    /// - `authorization_parameters` - [AuthorizationParameters]: Customize the authorization request.
    /// - `dpop_options` - Optional DPoP options for the request.
    pub async fn pushed_authorization_request_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        http_client: &H,
        mut authorization_parameters: AuthorizationParameters,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<PushedAuthorizationResponse> {
        if authorization_parameters.client_id.is_none() {
            authorization_parameters.client_id = Some(config.client.client_id.to_owned());
        }

        let authorization_parameters_map: HashMap<String, String> = authorization_parameters.into();

        let response = authenticated_post_async(
            config,
            crypto,
            AuthenticatedEndpoints::PushedAuthorization,
            RequestBody::Form(authorization_parameters_map),
            http_client,
            dpop_options,
        )
        .await?;

        let body = response
            .body
            .ok_or(OpenIdError::new_error("body expected in PAR response"))?;

        deserialize::<PushedAuthorizationResponse>(&body).or(Err(OpenIdError::new_error(
            "could not convert body to PushedAuthorizationResponse",
        )))
    }

    /// # Device Authorization Request
    ///
    /// Performs a device authorization request as defined in RFC 8628.
    /// Returns the device authorization response containing the `device_code` and `user_code`.
    ///
    /// - `config` - OpenID client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `http_client` - The HTTP client to make the request.
    /// - `request` - [DeviceAuthorizationRequest]: Device authorization request parameters.
    /// - `additional_parameters` - Optional additional parameters for the request.
    /// - `dpop_options` - Optional DPoP options for the request.
    pub async fn device_authorization_request_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        http_client: &H,
        request: DeviceAuthorizationRequest,
        additional_parameters: Option<HashMap<String, String>>,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<DeviceAuthorizationResponse> {
        let mut device_auth_parameters: HashMap<String, String> = HashMap::new();

        if let Some(additional_parameters) = additional_parameters {
            device_auth_parameters.extend(additional_parameters);
        }

        if request.client_id.is_none() {
            device_auth_parameters
                .insert("client_id".to_owned(), config.client.client_id.to_owned());
        }

        device_auth_parameters.extend::<HashMap<String, String>>(request.into());

        let response = authenticated_post_async(
            config,
            crypto,
            AuthenticatedEndpoints::DeviceAuthorization,
            RequestBody::Form(device_auth_parameters),
            http_client,
            dpop_options,
        )
        .await?;

        let body = response.body.ok_or(OpenIdError::new_error(
            "body expected in device authorization response",
        ))?;

        deserialize::<DeviceAuthorizationResponse>(&body).or(Err(OpenIdError::new_error(
            "could not convert body to DeviceAuthorizationResponse",
        )))
    }

    /// # Device Code Grant
    ///
    /// Performs a device code grant.
    ///
    /// - `config` - OpenID client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `http_client` - The HTTP client to make the request.
    /// - `device_code` - The device code.
    /// - `additional_parameters` - Optional additional parameters for the grant.
    /// - `dpop_options` - Optional DPoP options for the request.
    pub async fn device_code_grant_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        http_client: &H,
        device_code: &str,
        additional_parameters: Option<HashMap<String, String>>,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<TokenSet> {
        let mut device_code_grant_params = HashMap::new();
        if let Some(additional_parameters) = additional_parameters {
            device_code_grant_params.extend(additional_parameters);
        }
        device_code_grant_params.insert(
            "grant_type".to_owned(),
            "urn:ietf:params:oauth:grant-type:device_code".to_owned(),
        );
        device_code_grant_params.insert("device_code".to_owned(), device_code.to_owned());

        let tokenset = Client::grant_async(
            config,
            crypto,
            RequestBody::Form(device_code_grant_params),
            http_client,
            dpop_options,
        )
        .await?;

        validate_access_token_response(config, crypto, tokenset, &[], true)
    }

    /// # Client Credentials Grant
    ///
    /// Performs client credentials grant.
    ///
    /// - `config` - OpenID client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `http_client` - The HTTP client to make the request.
    /// - `additional_parameters` - Optional additional parameters for the grant.
    /// - `dpop_options` - Optional DPoP options for the request.
    pub async fn client_credentials_grant_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        http_client: &H,
        additional_parameters: Option<HashMap<String, String>>,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<TokenSet> {
        let mut client_credentials_parameters = HashMap::new();
        if let Some(additional_parameters) = additional_parameters {
            client_credentials_parameters.extend(additional_parameters);
        }
        client_credentials_parameters
            .insert("grant_type".to_owned(), "client_credentials".to_owned());

        let tokenset = Client::grant_async(
            config,
            crypto,
            RequestBody::Form(client_credentials_parameters),
            http_client,
            dpop_options,
        )
        .await?;

        validate_access_token_response(config, crypto, tokenset, &[], true)
    }

    /// # CIBA Authentication
    ///
    /// Performs a Client Initiated Backchannel Authentication (CIBA) request.
    /// Returns the CIBA authentication response containing the `auth_req_id`.
    ///
    /// - `config` - OpenID client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `http_client` - The HTTP client to make the request.
    /// - `request` - [CibaAuthRequest]: CIBA authentication request parameters.
    /// - `additional_parameters` - Optional additional parameters for the request.
    /// - `dpop_options` - Optional DPoP options for the request.
    pub async fn ciba_authentication_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        http_client: &H,
        request: CibaAuthRequest,
        additional_parameters: Option<HashMap<String, String>>,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<CibaAuthResponse> {
        let hint_count = [
            request.login_hint.is_some(),
            request.login_hint_token.is_some(),
            request.id_token_hint.is_some(),
        ]
        .iter()
        .filter(|&&h| h)
        .count();

        if hint_count != 1 {
            return Err(OpenIdError::new_error(
                "exactly one of login_hint, login_hint_token, or id_token_hint must be provided",
            ));
        }

        let mut ciba_parameters: HashMap<String, String> = HashMap::new();

        if let Some(additional_parameters) = additional_parameters {
            ciba_parameters.extend(additional_parameters);
        }

        ciba_parameters.extend::<HashMap<String, String>>(request.into());

        // Check scope after merging all parameters so that scope set via
        // additional_parameters is also accepted.
        if !ciba_parameters.contains_key("scope")
            || ciba_parameters.get("scope").is_some_and(|s| s.is_empty())
        {
            return Err(OpenIdError::new_error("scope is required for CIBA request"));
        }

        ciba_parameters.insert("client_id".to_owned(), config.client.client_id.to_owned());

        let response = authenticated_post_async(
            config,
            crypto,
            AuthenticatedEndpoints::BackChannelAuthentication,
            RequestBody::Form(ciba_parameters),
            http_client,
            dpop_options,
        )
        .await?;

        let body = response.body.ok_or(OpenIdError::new_error(
            "body expected in CIBA authentication response",
        ))?;

        let ciba_response = deserialize::<CibaAuthResponse>(&body)
            .map_err(|_| OpenIdError::new_error("could not convert body to CibaAuthResponse"))?;

        if ciba_response.auth_req_id.is_empty() {
            return Err(OpenIdError::new_client_error(
                "expected auth_req_id in CIBA Successful Response",
            ));
        }

        Ok(ciba_response)
    }

    /// # CIBA Grant
    ///
    /// Performs a CIBA token grant using the `auth_req_id` from a previous CIBA authentication.
    /// This method is used to poll for the token after the user has authenticated.
    ///
    /// - `config` - OpenID client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `http_client` - The HTTP client to make the request.
    /// - `auth_req_id` - The authentication request ID from CIBA authentication response.
    /// - `additional_parameters` - Optional additional parameters for the grant.
    /// - `dpop_options` - Optional DPoP options for the request.
    pub async fn ciba_grant_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        http_client: &H,
        auth_req_id: &str,
        additional_parameters: Option<HashMap<String, String>>,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<TokenSet> {
        let mut ciba_grant_params = HashMap::new();

        if let Some(additional_parameters) = additional_parameters {
            ciba_grant_params.extend(additional_parameters);
        }

        ciba_grant_params.insert(
            "grant_type".to_owned(),
            "urn:openid:params:grant-type:ciba".to_owned(),
        );

        ciba_grant_params.insert("auth_req_id".to_owned(), auth_req_id.to_owned());

        let tokenset = Client::grant_async(
            config,
            crypto,
            RequestBody::Form(ciba_grant_params),
            http_client,
            dpop_options,
        )
        .await?;

        validate_access_token_response(config, crypto, tokenset, &[], true)
    }

    /// # Introspection
    ///
    /// Performs an introspection request at Issuer's `introspection_endpoint`.
    ///
    /// - `config` - OpenID client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `http_client` - The HTTP client to make the request.
    /// - `token` - The token to introspect.
    /// - `token_type_hint` - Hint to which type of token is being introspected.
    /// - `additional_parameters` - Optional additional parameters for the introspection request.
    /// - `dpop_options` - Optional DPoP options for the request.
    pub async fn introspect_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        http_client: &H,
        token: &str,
        token_type_hint: Option<&str>,
        additional_parameters: Option<HashMap<String, String>>,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<HttpResponse> {
        let mut introspect_params = HashMap::new();

        if let Some(additional_parameters) = additional_parameters {
            introspect_params.extend(additional_parameters);
        }

        introspect_params.insert("token".to_owned(), token.to_owned());

        if let Some(hint) = token_type_hint {
            introspect_params.insert("token_type_hint".to_owned(), hint.to_owned());
        }

        authenticated_post_async(
            config,
            crypto,
            AuthenticatedEndpoints::Introspection,
            RequestBody::Form(introspect_params),
            http_client,
            dpop_options,
        )
        .await
    }

    /// # Revoke Token
    ///
    /// Performs token revocation at the revocation endpoint (RFC 7009).
    ///
    /// - `config` - OpenID client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `http_client` - The HTTP client to make the request.
    /// - `token` - The token to be revoked (access_token or refresh_token).
    /// - `token_type_hint` - Optional hint about the token type ("access_token" or "refresh_token").
    /// - `additional_parameters` - Optional additional parameters for the revocation request.
    /// - `dpop_options` - Optional DPoP options for the request.
    pub async fn revoke_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        http_client: &H,
        token: &str,
        token_type_hint: Option<&str>,
        additional_parameters: Option<HashMap<String, String>>,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<()> {
        let mut revoke_params = HashMap::new();

        if let Some(additional_parameters) = additional_parameters {
            revoke_params.extend(additional_parameters);
        }

        revoke_params.insert("token".to_owned(), token.to_owned());

        if let Some(hint) = token_type_hint {
            revoke_params.insert("token_type_hint".to_owned(), hint.to_owned());
        }

        let _response = authenticated_post_async(
            config,
            crypto,
            AuthenticatedEndpoints::Revocation,
            RequestBody::Form(revoke_params),
            http_client,
            dpop_options,
        )
        .await?;

        Ok(())
    }

    /// # Request Resource
    ///
    /// Makes a resource request using an access token.
    ///
    /// - `config` - OpenID client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `http_client` - The HTTP client to make the request.
    /// - `resource_url` - The URL of the resource to request.
    /// - `access_token` - The access token to use for authorization.
    /// - `is_mtls` - Boolean to indicate if the request should use mTLS.
    /// - `method` - HTTP method (default: GET).
    /// - `headers` - Optional additional headers for the request.
    /// - `body` - Optional request body.
    /// - `dpop_options` - Optional DPoP options for the request.
    #[allow(clippy::too_many_arguments)]
    pub async fn request_resource_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        http_client: &H,
        resource_url: Url,
        access_token: &str,
        is_mtls: bool,
        method: Option<HttpMethod>,
        headers: Option<HashMap<String, Vec<String>>>,
        body: Option<RequestBody>,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<HttpResponse> {
        if resource_url.scheme() != "https" && resource_url.scheme() != "http" {
            return Err(OpenIdError::new_error(
                "only http and https URL schemes are supported",
            ));
        }

        let mut request_headers = headers.unwrap_or_default();

        if request_headers
            .iter()
            .any(|(k, _)| k.to_lowercase() == "authorization")
        {
            return Err(OpenIdError::new_error(
                "Authorization header must not be present",
            ));
        }

        // Note: We are setting the scheme to DPoP since a key is passed in.
        // If the request fails when DPoP options is passed in
        // check if the dpop header is being set properly
        let token_type = if dpop_options.is_some() {
            "DPoP"
        } else {
            "Bearer"
        };

        request_headers.insert(
            "authorization".to_string(),
            vec![format!("{} {}", token_type, access_token)],
        );

        let mut request = HttpRequest::new()
            .url(resource_url)
            .mtls(is_mtls)
            .method(method.unwrap_or(HttpMethod::GET))
            .headers(request_headers);

        if let Some(body) = body {
            request.body = Some(body);
        }

        let mut http_builder = Http::default()
            .set_config(config)
            .set_check_expectations(false)
            .set_access_token(access_token);

        if let Some(dpop_options) = dpop_options {
            http_builder = http_builder.set_dpop(
                dpop_options,
                config.issuer.dpop_signing_alg_values_supported.as_ref(),
                config.options.clock_skew,
            );
        }

        http_builder
            .request_async(request, http_client, Some(crypto))
            .await
    }

    /// # Userinfo
    ///
    /// Fetches user information from the userinfo endpoint.
    ///
    /// - `config` - OpenID client configuration
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `http_client` - The HTTP client to make the request
    /// - `token_set` - TokenSet containing the access_token
    /// - `at_location` - Access token location
    /// - `method` - HTTP method (GET or POST, default: GET)
    /// - `additional_params` - Optional additional parameters
    /// - `dpop_options` - Optional DPoP options for the request.
    #[allow(clippy::too_many_arguments)]
    pub async fn userinfo_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        http_client: &H,
        token_set: &TokenSet,
        at_location: UserinfoTokenLocation,
        method: Option<HttpMethod>,
        additional_params: Option<HashMap<String, String>>,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<Value> {
        let access_token = token_set
            .access_token
            .as_ref()
            .ok_or_else(|| OpenIdError::new_error("access_token is required in token_set"))?;

        let method = method.unwrap_or(HttpMethod::GET);

        if !matches!(method, HttpMethod::GET | HttpMethod::POST) {
            return Err(OpenIdError::new_error(
                "userinfo method can only be GET or POST",
            ));
        }

        if matches!(at_location, UserinfoTokenLocation::Body) && !matches!(method, HttpMethod::POST)
        {
            return Err(OpenIdError::new_error(
                "can only send token via body on POST",
            ));
        }

        // Determine if JWT response is expected
        let expect_jwt = config.client.userinfo_signed_response_alg.is_some()
            || config.client.userinfo_encrypted_response_alg.is_some();

        // Determine endpoint URL (use mTLS if certificate-bound tokens)
        let mtls = config
            .client
            .tls_client_certificate_bound_access_tokens
            .is_some_and(|x| x);

        let mut url = if mtls {
            config
                .mtls_userinfo_endpoint()
                .or_else(|_| config.userinfo_endpoint())?
        } else {
            config.userinfo_endpoint()?
        };

        // Determine token type
        // token_type is normalized to lowercase during deserialization, but
        // the Authorization header scheme is case-sensitive per RFC 6750 §2.1.
        let token_type = if dpop_options.is_some() {
            "DPoP"
        } else {
            match token_set.token_type.as_deref() {
                Some("bearer") | Some("Bearer") | None => "Bearer",
                Some("dpop") => "DPoP",
                Some(other) => other,
            }
        };

        // Build headers
        let mut headers = HashMap::new();

        if expect_jwt {
            headers.insert("accept".to_string(), vec!["application/jwt".to_string()]);
        } else {
            headers.insert("accept".to_string(), vec!["application/json".to_string()]);
        }

        // Build request body and handle token delivery
        let mut form_body: HashMap<String, String> = HashMap::new();

        if at_location == UserinfoTokenLocation::Header {
            headers.insert(
                "authorization".to_string(),
                vec![format!("{} {}", token_type, access_token)],
            );
        } else {
            // Body
            headers.insert(
                "content-type".to_string(),
                vec!["application/x-www-form-urlencoded".to_string()],
            );
            form_body.insert("access_token".to_string(), access_token.to_owned());
        }

        // Handle additional params
        if let Some(params) = additional_params {
            match method {
                HttpMethod::GET => {
                    for (k, v) in params {
                        url.query_pairs_mut().append_pair(&k, &v);
                    }
                }
                HttpMethod::POST => {
                    for (k, v) in params {
                        form_body.insert(k, v);
                    }
                }
                _ => {}
            }
        }

        // Build request
        let mut request = HttpRequest::new()
            .url(url)
            .method(method)
            .headers(headers)
            .expect_raw_body();

        // Enable bearer token error handling
        request.expectations.bearer = true;
        request.mtls = mtls;

        if !form_body.is_empty() {
            request.body = Some(RequestBody::Form(form_body));
        }

        let mut http_builder = Http::default()
            .set_config(config)
            .set_access_token(access_token);

        if let Some(dpop_options) = dpop_options {
            http_builder = http_builder.set_dpop(
                dpop_options,
                config.issuer.dpop_signing_alg_values_supported.as_ref(),
                config.options.clock_skew,
            );
        }

        let response = http_builder
            .request_async(request, http_client, Some(crypto))
            .await?;

        // Parse response
        let body = response
            .body
            .ok_or_else(|| OpenIdError::new_error("userinfo response body was empty"))?;

        let payload: Value = if expect_jwt {
            let jwt_params = JwtValidationParameters {
                signing_keys: &config.issuer_jwks,
                check_header_alg: true,
                issuer_algs: &config.issuer.userinfo_signing_alg_values_supported,
                client_algs: config
                    .client
                    .userinfo_signed_response_alg
                    .clone()
                    .map(|alg| vec![alg]),
                fallback_algs: Some(vec!["RS256".to_owned()]),
                skew: config.options.clock_skew,
                tolerance: config.options.clock_tolerance,
            };

            let validated_jwt = validate_jwt(body, jwt_params, &config.jwe_keys, crypto)?;
            Value::Object(validated_jwt.payload.params)
        } else {
            deserialize::<Value>(&body)
                .map_err(|_| OpenIdError::new_error("failed to parse userinfo response as JSON"))?
        };

        // Per OpenID Connect Core Section 5.3.4: sub claim MUST always be present
        if payload.get("sub").is_none() {
            return Err(OpenIdError::new_error(
                "userinfo response is missing the required \"sub\" claim",
            ));
        }

        // Validate sub claim consistency with ID token
        if token_set.id_token.is_some() {
            if let Some(expected_sub) = token_set.claims().and_then(|c| c.get("sub").cloned()) {
                if let Some(actual_sub) = payload.get("sub") {
                    if expected_sub != *actual_sub {
                        return Err(OpenIdError::new_error(format!(
                            "userinfo sub mismatch, expected {}, got: {}",
                            expected_sub, actual_sub
                        )));
                    }
                }
            }
        }

        Ok(payload)
    }

    /// # Request Object
    ///
    /// Creates a JWT-secured Authorization Request (JAR - RFC 9101).
    /// The returned JWT can be used as the `request` parameter in authorization requests.
    ///
    /// - `config` - OpenID client configuration
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `key` - The specific key used to sign the request object. If not provided, a default will be selected from client secret or jwks.
    /// - `request_object` - The request object claims as a JSON Value (must be an object)
    ///
    /// Note: Encryption is not yet supported. Only signing is implemented.
    pub fn request_object<C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        key: Option<Jwk>,
        mut request_object: Value,
    ) -> OidcReturn<String> {
        if !request_object.is_object() {
            return Err(OpenIdError::new_error(
                "request_object must be a plain object",
            ));
        }

        // Get signing algorithm
        let alg = &config
            .client
            .request_object_signing_alg
            .clone()
            .unwrap_or("none".to_string());

        let typ = "oauth-authz-req+jwt";

        let now = unix_timestamp();

        // Add standard claims
        request_object["iss"] = Value::String(config.client.client_id.clone());
        request_object["aud"] = Value::String(config.issuer.issuer.clone());
        request_object["client_id"] = Value::String(config.client.client_id.clone());
        request_object["jti"] = Value::String(generate_random(None));
        request_object["iat"] = Value::Number(now.into());
        request_object["exp"] = Value::Number((now + 300).into());

        // Add nbf for FAPI clients
        if config.fapi {
            request_object["nbf"] = Value::Number(now.into());
        }

        let payload_str = request_object.to_string();

        // Handle unsigned JWT (alg = none)
        if alg == "none" {
            let header = format!("{{\"alg\":\"none\",\"typ\":\"{}\"}}", typ);
            let encoded_header = base64_url_encode(&header);
            let encoded_payload = base64_url_encode(&payload_str);
            return Ok(format!("{}.{}.", encoded_header, encoded_payload));
        }

        let jwk: Jwk;
        let include_kid = !alg.starts_with("HS");

        if let Some(key) = key {
            jwk = key;
        } else {
            if alg.starts_with("HS") {
                let secret = get_client_secret(config)?;
                jwk = Jwk::from_symmetric_key(secret.as_bytes());
            } else {
                let jwks_key: Option<Jwk> = config
                    .client_jwks
                    .iter()
                    .find(|key| key.get_param("alg").and_then(|a| a.as_str()) == Some(alg))
                    .cloned();

                match jwks_key {
                    Some(key) => jwk = key,
                    None => {
                        return Err(OpenIdError::new_error(format!(
                            "no private key available for signing with algorithm {}",
                            alg
                        )));
                    }
                }
            }
        }

        // Build header
        let mut header_params = serde_json::Map::new();
        header_params.insert("alg".to_string(), Value::String(alg.clone()));
        header_params.insert("typ".to_string(), Value::String(typ.to_string()));

        if include_kid {
            if let Some(kid) = jwk.get_param("kid").and_then(|v| v.as_str()) {
                header_params.insert("kid".to_string(), Value::String(kid.to_string()));
            }
        }

        let header = Header {
            params: header_params,
        };

        let payload = Payload {
            params: request_object.as_object().cloned().unwrap_or_default(),
        };

        // Sign the JWT
        let signed = crypto
            .jws_serialize(payload, header, &jwk)
            .map_err(|e| OpenIdError::new_error(format!("failed to sign request object: {}", e)))?;

        // Check if encryption is configured
        if config.client.request_object_encryption_alg.is_some() {
            return Err(OpenIdError::new_error(
                "request object encryption is not yet supported in the new client",
            ));
        }

        Ok(signed)
    }

    /// # From URI
    ///
    /// Fetches client metadata from a registration_client_uri.
    /// This is used to retrieve client configuration after dynamic registration.
    ///
    /// - `http_client` - The HTTP client to make the request.
    /// - `registration_client_uri` - The URL to fetch client metadata from.
    /// - `registration_access_token` - Optional access token for authentication.
    pub async fn from_uri_async<H: OidcHttpClient>(
        http_client: &H,
        registration_client_uri: &str,
        registration_access_token: Option<&str>,
    ) -> OidcReturn<ClientRegistrationResponse> {
        let url = Url::parse(registration_client_uri)
            .map_err(|e| OpenIdError::new_error(format!("Invalid registration_client_uri: {e}")))?;

        let mut headers = HashMap::new();
        headers.insert("accept".to_string(), vec!["application/json".to_string()]);

        if let Some(rat) = registration_access_token {
            headers.insert("authorization".to_string(), vec![format!("Bearer {}", rat)]);
        }

        let request = HttpRequest::new()
            .url(url)
            .method(HttpMethod::GET)
            .headers(headers)
            .expect_json()
            .expect_status_code(200);

        let response = Http::default()
            .request_async(request, http_client, None)
            .await?;

        let body = response
            .body
            .ok_or_else(|| OpenIdError::new_error("empty response from registration_client_uri"))?;

        deserialize::<ClientRegistrationResponse>(&body)
            .map_err(|e| OpenIdError::new_error(format!("failed to parse client metadata: {}", e)))
    }

    /// # Register
    ///
    /// Performs dynamic client registration (RFC 7591) at the issuer's registration_endpoint.
    ///
    /// - `http_client` - The HTTP client to make the request.
    /// - `issuer` - The issuer metadata (must have registration_endpoint).
    /// - `registration_request` - The client registration request parameters.
    /// - `initial_access_token` - Optional initial access token for protected registration.
    pub async fn register_async<H: OidcHttpClient>(
        http_client: &H,
        issuer: &IssuerMetadata,
        registration_request: ClientRegistrationRequest,
        initial_access_token: Option<&str>,
    ) -> OidcReturn<ClientRegistrationResponse> {
        let registration_endpoint = issuer.registration_endpoint.as_ref().ok_or_else(|| {
            OpenIdError::new_error("registration_endpoint must be configured on the issuer")
        })?;

        let url = Url::parse(registration_endpoint)
            .map_err(|e| OpenIdError::new_error(format!("Invalid registration_endpoint: {e}")))?;

        let body = serde_json::to_string(&registration_request).map_err(|e| {
            OpenIdError::new_error(format!("failed to serialize registration request: {}", e))
        })?;

        let mut headers = HashMap::new();
        headers.insert("accept".to_string(), vec!["application/json".to_string()]);
        headers.insert(
            "content-type".to_string(),
            vec!["application/json".to_string()],
        );

        if let Some(iat) = initial_access_token {
            headers.insert("authorization".to_string(), vec![format!("Bearer {}", iat)]);
        }

        let request = HttpRequest::new()
            .url(url)
            .method(HttpMethod::POST)
            .headers(headers)
            .expect_json()
            .expect_status_code(201);

        let mut request = request;
        request.body = Some(RequestBody::Json(body));

        let response = Http::default()
            .request_async(request, http_client, None)
            .await?;

        let body = response
            .body
            .ok_or_else(|| OpenIdError::new_error("empty response from registration_endpoint"))?;

        deserialize::<ClientRegistrationResponse>(&body).map_err(|e| {
            OpenIdError::new_error(format!("failed to parse registration response: {}", e))
        })
    }

    /// # Token Exchange
    ///
    /// Performs a Token Exchange Grant (RFC 8693).
    /// *This method is currently a stub outlining how to extend this client.*
    ///
    /// - `config` - OpenID client configuration.
    /// - `crypto` - The crypto backend to use for OpenID crypto operations.
    /// - `http_client` - The HTTP client to make the request.
    /// - `subject_token` - The security token to exchange.
    /// - `subject_token_type` - The type identifier of the subject token.
    /// - `additional_parameters` - Optional additional parameters for the token exchange grant.
    /// - `dpop_options` - Optional DPoP options for the request.
    pub async fn token_exchange_async<H: OidcHttpClient, C: OpenIdCrypto>(
        config: &OpenIdClientConfiguration,
        crypto: &C,
        http_client: &H,
        subject_token: &str,
        subject_token_type: &str,
        additional_parameters: Option<HashMap<String, String>>,
        dpop_options: Option<&DPoPOptions>,
    ) -> OidcReturn<TokenSet> {
        let mut params = HashMap::new();
        if let Some(additional_parameters) = additional_parameters {
            params.extend(additional_parameters);
        }
        params.insert(
            "grant_type".to_owned(),
            "urn:ietf:params:oauth:grant-type:token-exchange".to_owned(),
        );
        params.insert("subject_token".to_owned(), subject_token.to_owned());
        params.insert(
            "subject_token_type".to_owned(),
            subject_token_type.to_owned(),
        );

        let tokenset = Client::grant_async(
            config,
            crypto,
            RequestBody::Form(params),
            http_client,
            dpop_options,
        )
        .await?;

        // RFC 8693 Section 2.2.1 specifies `issued_token_type` is REQUIRED in the response
        if tokenset
            .other
            .as_ref()
            .and_then(|other| other.get("issued_token_type"))
            .and_then(|val| val.as_str())
            .is_none()
        {
            return Err(OpenIdError::new_error(
                "token exchange response is missing the required 'issued_token_type' parameter",
            ));
        }

        // `token_type` is also REQUIRED in RFC 8693, with 'N/A' allowed if no type applies
        if tokenset.token_type.is_none() {
            return Err(OpenIdError::new_error(
                "token exchange response is missing the required 'token_type' parameter",
            ));
        }

        Ok(tokenset)
    }
}

fn get_client_secret(config: &OpenIdClientConfiguration) -> OidcReturn<String> {
    match &config.auth {
        ClientAuth::ClientSecretBasic { client_secret }
        | ClientAuth::ClientSecretPost { client_secret }
        | ClientAuth::ClientSecretJwt { client_secret, .. } => Ok(client_secret.to_string()),
        _ => Err(OpenIdError::new_error(
            "client secret not available for symmetric signing",
        )),
    }
}

fn html_escape(input: &str) -> String {
    input
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#x27;")
}

async fn authenticated_post_async<H: OidcHttpClient, C: OpenIdCrypto>(
    config: &OpenIdClientConfiguration,
    crypto: &C,
    endpoint: AuthenticatedEndpoints,
    body: RequestBody,
    http_client: &H,
    dpop_options: Option<&DPoPOptions>,
) -> OidcReturn<HttpResponse> {
    config.check_authentication_support(&endpoint)?;

    let mut request = HttpRequest::new();

    request.body = Some(body);

    config.auth.authenticate(
        &config.client.client_id,
        &config.options,
        &config.issuer,
        &mut request,
        crypto,
    )?;

    request = request.header("content-type", "application/x-www-form-urlencoded");

    let is_mtls_auth = config.auth.get_auth_method() == AuthMethods::TlsClientAuth
        || config.auth.get_auth_method() == AuthMethods::SelfSignedTlsClientAuth;

    request.mtls = is_mtls_auth
        || config
            .client
            .tls_client_certificate_bound_access_tokens
            .is_some_and(|tccbat| tccbat);

    request.url = match (&endpoint, request.mtls) {
        // Regular Requests
        (AuthenticatedEndpoints::Token, false) => config.token_endpoint()?,
        (AuthenticatedEndpoints::Introspection, false) => config.introspection_endpoint()?,
        (AuthenticatedEndpoints::Revocation, false) => config.revocation_endpoint()?,
        (AuthenticatedEndpoints::PushedAuthorization, false) => config.par_endpoint()?,
        (AuthenticatedEndpoints::DeviceAuthorization, false) => {
            config.device_authorization_endpoint()?
        }
        (AuthenticatedEndpoints::BackChannelAuthentication, false) => {
            config.backchannel_authentication_endpoint()?
        }
        // MTLS Requests
        (AuthenticatedEndpoints::Token, true) => config.mtls_token_endpoint()?,
        (AuthenticatedEndpoints::Introspection, true) => config.mtls_introspection_endpoint()?,
        (AuthenticatedEndpoints::Revocation, true) => config.mtls_revocation_endpoint()?,
        (AuthenticatedEndpoints::PushedAuthorization, true) => config.mtls_par_endpoint()?,
        (AuthenticatedEndpoints::DeviceAuthorization, true) => {
            config.mtls_device_authorization_endpoint()?
        }
        (AuthenticatedEndpoints::BackChannelAuthentication, true) => {
            config.mtls_backchannel_authentication_endpoint()?
        }
    };

    match endpoint {
        AuthenticatedEndpoints::Revocation => {
            // No body response is expected for revocation
        }
        _ => {
            request = request.header("accept", "application/json");
        }
    };

    request.method = HttpMethod::POST;

    let mut binding = Http::default().set_config(config);

    if let Some(dpop_options) = dpop_options {
        binding = binding.set_dpop(
            dpop_options,
            config.issuer.dpop_signing_alg_values_supported.as_ref(),
            config.options.clock_skew,
        );
    }

    binding
        .request_async(request, http_client, Some(crypto))
        .await
}