-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAuthenticationClient.ts
More file actions
3935 lines (3837 loc) · 130 KB
/
AuthenticationClient.ts
File metadata and controls
3935 lines (3837 loc) · 130 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
import base64url from "base64url";
import { createSecretKey } from "crypto";
import { IncomingMessage, ServerResponse } from "http";
import { compactVerify } from "jose";
import { TextDecoder } from "util";
import {
AccessToken,
AuthURLParams,
AuthUrlResult,
IDToken,
LoginTransaction,
LogoutURLParams,
OIDCTokenResponse,
} from "./AuthenticationClientInterface";
import {
AuthenticationClientInitOptions,
DEFAULT_COOKIE_KEY,
DEFAULT_SCOPE,
DEFAULT_SOCKET_URI,
} from "./AuthenticationClientOptions";
import {
createQueryParams,
domainC14n,
generateRandomString,
JoseKey,
JWKSObject,
parseJWKS,
serialize,
} from "./utils";
import sha256 from "crypto-js/sha256";
import CryptoJS from "crypto-js";
import { AuthenticationHttpClient } from "./AutherticationHttpClient";
import {
Cas20ValidationFailureResult,
Cas20ValidationSuccessResult,
CasParams,
LogoutParams,
OauthParams,
OidcParams,
} from "./utils/types";
import { SignInOptionsDto, SignUpOptionsDto, SignUpProfileDto } from "./models";
// ==== AUTO GENERATED AUTHENTICATION IMPORTS BEGIN ====
import type { ApprovalDetailRes } from "./models/ApprovalDetailRes";
import type { AuthorizedResourcePaginatedRespDto } from "./models/AuthorizedResourcePaginatedRespDto";
import type { BatchCreateApprovalReq } from "./models/BatchCreateApprovalReq";
import type { BindByAccountIdInputApi } from "./models/BindByAccountIdInputApi";
import type { BindByAccountInputApi } from "./models/BindByAccountInputApi";
import type { BindByAccountsInputApi } from "./models/BindByAccountsInputApi";
import type { BindByEmailCodeInputApi } from "./models/BindByEmailCodeInputApi";
import type { BindByPhoneCodeInputApi } from "./models/BindByPhoneCodeInputApi";
import type { BindByRegiserInputApi } from "./models/BindByRegiserInputApi";
import type { BindEmailDto } from "./models/BindEmailDto";
import type { BindPhoneDto } from "./models/BindPhoneDto";
import type { ChangePushCodeStatusDto } from "./models/ChangePushCodeStatusDto";
import type { ChangeQRCodeStatusDto } from "./models/ChangeQRCodeStatusDto";
import type { CheckPermissionArrayResourceDto } from "./models/CheckPermissionArrayResourceDto";
import type { CheckPermissionStringResourceDto } from "./models/CheckPermissionStringResourceDto";
import type { CheckPermissionTreeResourceDto } from "./models/CheckPermissionTreeResourceDto";
import type { CheckPushCodeStatusRespDto } from "./models/CheckPushCodeStatusRespDto";
import type { CheckQRCodeStatusRespDto } from "./models/CheckQRCodeStatusRespDto";
import type { CheckResourcePermissionsRespDto } from "./models/CheckResourcePermissionsRespDto";
import type { CommonResponseDto } from "./models/CommonResponseDto";
import type { CreateApprovalReq } from "./models/CreateApprovalReq";
import type { CreateApprovalRes } from "./models/CreateApprovalRes";
import type { DecryptDouyinMiniProgramDataDto } from "./models/DecryptDouyinMiniProgramDataDto";
import type { DecryptDouyinMiniProgramDataRespDto } from "./models/DecryptDouyinMiniProgramDataRespDto";
import type { DecryptWechatMiniProgramDataDto } from "./models/DecryptWechatMiniProgramDataDto";
import type { DecryptWechatMiniProgramDataRespDto } from "./models/DecryptWechatMiniProgramDataRespDto";
import type { DeleteAccounDto } from "./models/DeleteAccounDto";
import type { EnablePermissionApplyApplicationListRes } from "./models/EnablePermissionApplyApplicationListRes";
import type { EnablePermissionApplyRoleListRes } from "./models/EnablePermissionApplyRoleListRes";
import type { ExchangeTokenSetWithQRcodeTicketDto } from "./models/ExchangeTokenSetWithQRcodeTicketDto";
import type { GenePushCodeRespDto } from "./models/GenePushCodeRespDto";
import type { GeneQRCodeRespDto } from "./models/GeneQRCodeRespDto";
import type { GenerateBindExtIdpLinkRespDto } from "./models/GenerateBindExtIdpLinkRespDto";
import type { GenerateInvitationLinkRespDto } from "./models/GenerateInvitationLinkRespDto";
import type { GenerateInviteeTokenRespDto } from "./models/GenerateInviteeTokenRespDto";
import type { GenerateQrcodeDto } from "./models/GenerateQrcodeDto";
import type { GetAccessibleAppsRespDto } from "./models/GetAccessibleAppsRespDto";
import type { GetAlipayAuthInfoRespDto } from "./models/GetAlipayAuthInfoRespDto";
import type { GetAuthenticationOptionsRespDto } from "./models/GetAuthenticationOptionsRespDto";
import type { GetCaptchaCodeRespDto } from "./models/GetCaptchaCodeRespDto";
import type { GetCountryListRespDto } from "./models/GetCountryListRespDto";
import type { GetExtIdpsRespDto } from "./models/GetExtIdpsRespDto";
import type { GetIdentitiesRespDto } from "./models/GetIdentitiesRespDto";
import type { GetInviteeContextRespDto } from "./models/GetInviteeContextRespDto";
import type { GetLoggedInAppsRespDto } from "./models/GetLoggedInAppsRespDto";
import type { GetLoginHistoryRespDto } from "./models/GetLoginHistoryRespDto";
import type { GetPublicAccountDataRespDto } from "./models/GetPublicAccountDataRespDto";
import type { GetRegistrationOptionsRespDto } from "./models/GetRegistrationOptionsRespDto";
import type { GetSecurityInfoRespDto } from "./models/GetSecurityInfoRespDto";
import type { GetTenantListRespDto } from "./models/GetTenantListRespDto";
import type { GetUniversalInvitationJoinRespDto } from "./models/GetUniversalInvitationJoinRespDto";
import type { GetUniversalInvitationPublicConfigRespDto } from "./models/GetUniversalInvitationPublicConfigRespDto";
import type { GetUserAuthResourceListRespDto } from "./models/GetUserAuthResourceListRespDto";
import type { GetUserAuthResourcePermissionListDto } from "./models/GetUserAuthResourcePermissionListDto";
import type { GetUserAuthResourcePermissionListRespDto } from "./models/GetUserAuthResourcePermissionListRespDto";
import type { GetUserAuthResourceStructDto } from "./models/GetUserAuthResourceStructDto";
import type { GetUserAuthResourceStructRespDto } from "./models/GetUserAuthResourceStructRespDto";
import type { GroupListRespDto } from "./models/GroupListRespDto";
import type { InitiatedApprovalListRes } from "./models/InitiatedApprovalListRes";
import type { InvitationLinkDto } from "./models/InvitationLinkDto";
import type { IsSuccessRespDto } from "./models/IsSuccessRespDto";
import type { LoginTokenRespDto } from "./models/LoginTokenRespDto";
import type { LoginTokenResponseDataDto } from "./models/LoginTokenResponseDataDto";
import type { PasswordResetVerifyResp } from "./models/PasswordResetVerifyResp";
import type { PolicyInviteeJoinedDto } from "./models/PolicyInviteeJoinedDto";
import type { PublicAccountSwitchLoginDto } from "./models/PublicAccountSwitchLoginDto";
import type { ResetPasswordDto } from "./models/ResetPasswordDto";
import type { RevokeDeviceSessionDto } from "./models/RevokeDeviceSessionDto";
import type { RoleListRespDto } from "./models/RoleListRespDto";
import type { SendEmailDto } from "./models/SendEmailDto";
import type { SendEmailRespDto } from "./models/SendEmailRespDto";
import type { SendSMSDto } from "./models/SendSMSDto";
import type { SendSMSRespDto } from "./models/SendSMSRespDto";
import { SigninByCredentialsDto } from "./models/SigninByCredentialsDto";
import type { SigninByMobileDto } from "./models/SigninByMobileDto";
import type { SignInByPushDto } from "./models/SignInByPushDto";
import { SignUpDto } from "./models/SignUpDto";
import type { SystemInfoResp } from "./models/SystemInfoResp";
import type { TerminalSessionRespDto } from "./models/TerminalSessionRespDto";
import type { UnbindDeviceDto } from "./models/UnbindDeviceDto";
import type { UnbindEmailDto } from "./models/UnbindEmailDto";
import type { UnbindPhoneDto } from "./models/UnbindPhoneDto";
import type { UniversalInvitationUserJoinDto } from "./models/UniversalInvitationUserJoinDto";
import type { UnlinkExtIdpDto } from "./models/UnlinkExtIdpDto";
import type { UpdateEmailDto } from "./models/UpdateEmailDto";
import type { UpdatePasswordDto } from "./models/UpdatePasswordDto";
import type { UpdatePhoneDto } from "./models/UpdatePhoneDto";
import type { UpdateUserProfileDto } from "./models/UpdateUserProfileDto";
import type { UserDepartmentPaginatedRespDto } from "./models/UserDepartmentPaginatedRespDto";
import type { UserSingleRespDto } from "./models/UserSingleRespDto";
import type { ValidatePasswordDto } from "./models/ValidatePasswordDto";
import type { ValidatePasswordRespDto } from "./models/ValidatePasswordRespDto";
import type { VerifyAuthenticationDto } from "./models/VerifyAuthenticationDto";
import type { VerifyAuthenticationResultRespDto } from "./models/VerifyAuthenticationResultRespDto";
import type { VerifyDeleteAccountRequestDto } from "./models/VerifyDeleteAccountRequestDto";
import type { VerifyDeleteAccountRequestRespDto } from "./models/VerifyDeleteAccountRequestRespDto";
import type { VerifyInviteCodeDto } from "./models/VerifyInviteCodeDto";
import type { VerifyRegistrationDto } from "./models/VerifyRegistrationDto";
import type { VerifyRegistrationResultRespDto } from "./models/VerifyRegistrationResultRespDto";
import type { VerifyResetPasswordRequestDto } from "./models/VerifyResetPasswordRequestDto";
import type { VerifyUpdateEmailRequestDto } from "./models/VerifyUpdateEmailRequestDto";
import type { VerifyUpdateEmailRequestRespDto } from "./models/VerifyUpdateEmailRequestRespDto";
import type { VerifyUpdatePhoneRequestDto } from "./models/VerifyUpdatePhoneRequestDto";
import type { VerifyUpdatePhoneRequestRespDto } from "./models/VerifyUpdatePhoneRequestRespDto";
import type { WechatLoginTokenRespDto } from "./models/WechatLoginTokenRespDto";
import type { WechatMobileAuthByCodeIdentityInput } from "./models/WechatMobileAuthByCodeIdentityInput";
import type { GeneFastpassQRCodeRespDto } from "./models/GeneFastpassQRCodeRespDto";
import type { GetFastpassQRCodeRelationAppsRespDto } from "./models/GetFastpassQRCodeRelationAppsRespDto";
import type { GetPushCodeRelationAppsDto } from "./models/GetPushCodeRelationAppsDto";
import type { GetPushCodeRelationAppsRespDto } from "./models/GetPushCodeRelationAppsRespDto";
import type { SignInFastpassDto } from "./models/SignInFastpassDto";
import type { AppQRCodeLoginDto } from "./models/AppQRCodeLoginDto";
import type { CheckDeviceCredentialIdDto } from "./models/CheckDeviceCredentialIdDto";
import type { ListDeviceCredentialDto } from "./models/ListDeviceCredentialDto";
import type { ListWebAuthnAuthenticatorDeviceDataDto } from "./models/ListWebAuthnAuthenticatorDeviceDataDto";
import type { PreCheckCodeDto } from "./models/PreCheckCodeDto";
import type { PreCheckCodeRespDto } from "./models/PreCheckCodeRespDto";
import type { RemoveDeviceCredentialDto } from "./models/RemoveDeviceCredentialDto";
import type { UpdatePasskeyDto } from "./models/UpdatePasskeyDto";
import type { WebAuthnCheckValidCredentialsByCredIdsRespDto } from "./models/WebAuthnCheckValidCredentialsByCredIdsRespDto";
import type { WebAuthnRemoveCredentialDto } from "./models/WebAuthnRemoveCredentialDto";
import type { LegacyExchangeTokenParams } from "./models/LegacyExchangeTokenParams";
import type { LegacyExchangeTokenResponse } from "./models/LegacyExchangeTokenResponse";
import type { MfaTokenIntrospectEndpointParams } from "./models/MfaTokenIntrospectEndpointParams";
import type { MfaTokenIntrospectResponse } from "./models/MfaTokenIntrospectResponse";
import type { EnrollFactorDto } from "./models/EnrollFactorDto";
import type { EnrollFactorRespDto } from "./models/EnrollFactorRespDto";
import type { GetFactorRespDto } from "./models/GetFactorRespDto";
import type { ListEnrolledFactorsRespDto } from "./models/ListEnrolledFactorsRespDto";
import type { ListFactorsToEnrollRespDto } from "./models/ListFactorsToEnrollRespDto";
import type { MfaOtpVerityDto } from "./models/MfaOtpVerityDto";
import type { MfaOtpVerityRespDto } from "./models/MfaOtpVerityRespDto";
import type { ResetFactorDto } from "./models/ResetFactorDto";
import type { ResetFactorRespDto } from "./models/ResetFactorRespDto";
import type { SendEnrollFactorRequestDto } from "./models/SendEnrollFactorRequestDto";
import type { SendEnrollFactorRequestRespDto } from "./models/SendEnrollFactorRequestRespDto";
import type { FinalizeWebAuthnLoginDto } from "./models/FinalizeWebAuthnLoginDto";
// ==== AUTO GENERATED AUTHENTICATION IMPORTS END ====
import WebSocket from "ws";
import type { GetWechatAccessTokenDto } from "./models/GetWechatAccessTokenDto";
import type { GetWechatAccessTokenRespDto } from "./models/GetWechatAccessTokenRespDto";
import type { GetWechatAccessTokenInfoRespDto } from "./models/GetWechatAccessTokenInfoRespDto";
const pkg = require("../package.json");
export class AuthenticationClient {
private readonly options: Required<AuthenticationClientInitOptions>;
private readonly httpClient: AuthenticationHttpClient;
private wsMap: {
[propName: string]: {
socket: WebSocket;
lockConnect: boolean;
timeConnect: number;
};
};
private eventBus: { [propName: string]: [Function, Function][] };
constructor(options: AuthenticationClientInitOptions) {
options.cookieKey = options.cookieKey ?? DEFAULT_COOKIE_KEY;
options.scope = options.scope ?? DEFAULT_SCOPE;
options.protocol = options.protocol ?? "oidc";
options.tokenEndPointAuthMethod =
options.tokenEndPointAuthMethod ?? "client_secret_post";
options.introspectionEndPointAuthMethod =
options.introspectionEndPointAuthMethod ?? "client_secret_post";
options.revocationEndPointAuthMethod =
options.revocationEndPointAuthMethod ?? "client_secret_post";
options.timeout = options.timeout || 10000;
options.retryTimes = options.retryTimes ?? 5;
options.socketUri = options.socketUri ?? DEFAULT_SOCKET_URI;
if (!options.scope?.includes("openid")) {
throw new Error("scope 中必须包含 openid");
}
// 判断必传参数
if (!options.appId) {
throw new Error(
"Init AuthenticationClient failed: appId is not provided"
);
}
if (!options.appHost) {
throw new Error(
"Init AuthenticationClient failed: appHost is not provided"
);
}
if (options.tokenEndPointAuthMethod !== "none" && !options.appSecret) {
throw new Error(
`Init AuthenticationClient failed: appSecret is not provided when tokenEndPointAuthMethod is not "none"`
);
}
this.options = options as any;
this.options.appHost = domainC14n(options.appHost);
this.httpClient = new AuthenticationHttpClient(this.options);
this.wsMap = {};
this.eventBus = {};
}
/**
* 将用户浏览器重定向到 Authing 的认证发起 URL 进行认证,利用 Cookie 将上下文信息传递到应用回调端点
*
* @param res http 响应对象,用于设置上下文 Cookie 并进行重定向
*
* @param options.scope 应用侧向 Authing 请求的权限,覆盖初始化参数中的对应设置
* @param options.state 中间状态标识符,默认自动生成
* @param options.nonce 出现在 ID Token 中的随机字符串,默认自动生成
* @param options.redirectUri 回调地址,覆盖初始化参数中的对应设置
* @param options.forced 即便用户已经登录也强制显示登录页
*/
public async loginWithRedirect(
res: ServerResponse,
options: {
scope?: string;
state?: string;
nonce?: string;
redirectUri?: string;
forced?: boolean;
} = {}
): Promise<void> {
const { url, state, nonce } = this.buildAuthorizeUrl(options);
res.setHeader("Location", url);
const tx: LoginTransaction = {
state,
nonce,
redirectUri: options.redirectUri ?? this.options.redirectUri,
};
// 设置中间态 cookie 用来在回调端点验证认证结果
res.setHeader(
"Set-Cookie",
`${this.options.cookieKey}=${base64url.encode(
JSON.stringify(tx)
)}; HttpOnly; SameSite=Lax`
);
res.writeHead(302).end();
}
/**
* 在应用回调端点处理认证返回结果,利用 Cookie 中传递的上下文信息进行安全验证,并获取用户登录态
*
* @param req http 请求对象,用于获取认证结果和上下文 Cookie
* @param res http 响应对象,只用于清除上下文 Cookie
*/
public async handleRedirectCallback(
req: IncomingMessage,
res: ServerResponse
): Promise<OIDCTokenResponse> {
if (!req.url) {
throw new Error("req 对象没有 url");
}
const url = new URL(req.url, "http://dummy");
const error = url.searchParams.get("error");
if (error) {
throw new Error(
`认证服务器返回错误 ${error}: ${url.searchParams.get(
"error_description"
)}`
);
}
const code = url.searchParams.get("code");
if (!code) {
throw new Error("认证服务器未返回授权码");
}
const cookieKey = `${this.options.cookieKey}=`;
const txStr = (req.headers["cookie"] ?? req.headers["Cookie"])
?.toString()
.split("; ")
.find((item) => item.startsWith(cookieKey))
?.substring(cookieKey.length);
if (!txStr) {
throw new Error("Cookie 中没有中间态,认证失败");
}
const tx: LoginTransaction = JSON.parse(base64url.decode(txStr));
// 清除中间态 cookie
res.setHeader(
"Set-Cookie",
`${this.options.cookieKey}=; HttpOnly; SameSite=Lax; Max-Age=0`
);
const state = url.searchParams.get("state");
if (state !== tx.state) {
throw new Error("state 验证失败");
}
const loginState = await this.getAccessTokenByCode(code);
return loginState;
}
/**
* @description 当用户完成登录之后,保存用户的 Access Token,后续请求会带上此 token
*
*/
public setAccessToken(accessToken: string) {
this.options.accessToken = accessToken;
}
private _generateTokenRequest(params: { [x: string]: string }) {
let ret: any = {};
// 删掉所有 undefined 的 kv
Object.keys(params).map((key) => {
if (typeof params[key] !== "undefined") {
ret[key] = params[key];
}
});
let p = new URLSearchParams(ret);
return p.toString();
}
/**
* @param {string} code 授权码 code
* @param {string} codeVerifier 校验码 codeVerifier
*/
private async _getAccessTokenByCodeWithClientSecretPost(
code: string,
codeVerifier?: string
) {
const qstr = this._generateTokenRequest({
client_id: this.options.appId,
client_secret: this.options.appSecret,
grant_type: "authorization_code",
code,
redirect_uri: this.options.redirectUri,
code_verifier: codeVerifier!,
});
let api = "";
if (this.options.protocol === "oidc") {
api = `/oidc/token`;
} else if (this.options.protocol === "oauth") {
api = `/oauth/token`;
}
let tokenSet = await this.httpClient.request({
method: "POST",
url: api,
data: qstr,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
return tokenSet;
}
private _generateBasicAuthToken(appId?: string, secret?: string) {
let id = appId || this.options.appId;
let s = secret || this.options.appSecret;
let token = "Basic " + Buffer.from(id + ":" + s).toString("base64");
return token;
}
/**
* @param {string} code 授权码 code
* @param {string} codeVerifier 校验码 codeVerifier
*/
private async _getAccessTokenByCodeWithClientSecretBasic(
code: string,
codeVerifier?: string
) {
let api = "";
if (this.options.protocol === "oidc") {
api = `/oidc/token`;
} else if (this.options.protocol === "oauth") {
api = `/oauth/token`;
}
const qstr = this._generateTokenRequest({
grant_type: "authorization_code",
code,
redirect_uri: this.options.redirectUri,
code_verifier: codeVerifier!,
});
let tokenSet = await this.httpClient.request({
data: qstr,
method: "POST",
url: api,
headers: {
Authorization: this._generateBasicAuthToken(),
},
});
return tokenSet;
}
/**
* @param {string} code 授权码 code
* @param {string} codeVerifier 校验码 codeVerifier
*/
private async _getAccessTokenByCodeWithNone(
code: string,
codeVerifier?: string
) {
let api = "";
if (this.options.protocol === "oidc") {
api = `/oidc/token`;
} else if (this.options.protocol === "oauth") {
api = `/oauth/token`;
}
const qstr = this._generateTokenRequest({
client_id: this.options.appId,
grant_type: "authorization_code",
code,
redirect_uri: this.options.redirectUri,
code_verifier: codeVerifier!,
});
let tokenSet = await this.httpClient.request({
method: "POST",
url: api,
data: qstr,
});
return tokenSet;
}
/**
* 使用授权码 Code 获取用户的 Token 信息。
*
* @param code 授权码 Code,用户在认证成功后,Authing 会将授权码 Code 发送到回调地址,详情请见使用 OIDC 授权码模式,每个 Code 只能使用一次。
* @param options.codeVerifier 校验码原始值,不是摘要值。
* @returns
*/
public async getAccessTokenByCode(
code: string,
options?: { codeVerifier?: string }
): Promise<OIDCTokenResponse> {
if (!["oauth", "oidc"].includes(this.options.protocol)) {
throw new Error(
"初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc,请检查参数"
);
}
if (
!this.options.appSecret &&
this.options.tokenEndPointAuthMethod !== "none"
) {
throw new Error(
"请在初始化 AuthenticationClient 时传入 appId 和 secret 参数"
);
}
if (this.options.tokenEndPointAuthMethod === "client_secret_post") {
return await this._getAccessTokenByCodeWithClientSecretPost(
code,
options?.codeVerifier
);
}
if (this.options.tokenEndPointAuthMethod === "client_secret_basic") {
return await this._getAccessTokenByCodeWithClientSecretBasic(
code,
options?.codeVerifier
);
}
if (this.options.tokenEndPointAuthMethod === "none") {
return await this._getAccessTokenByCodeWithNone(
code,
options?.codeVerifier
);
} else {
throw new Error(
"不支持的 tokenEndPointAuthMethod: " +
this.options.tokenEndPointAuthMethod
);
}
}
/**
* 使用编程访问账号获取具备权限的 Access Token。
*
* @param scope 权限项目,空格分隔的字符串,每一项代表一个权限。详情请见机器间(M2M)授权。
* @param options.accessKey 编程访问账号 AccessKey,如果不传默认使用初始化 SDK 时传入的 appId。
* @param options.secretKey 编程访问账号 SecretKey,如果不传默认使用初始化 SDK 时传入的 appSecret。
* @returns
*/
public async getAccessTokenByClientCredentials(
scope: string,
options?: {
accessKey: string;
accessSecret: string;
}
) {
if (!scope) {
throw new Error(
"请传入 scope 参数,请看文档:https://docs.authing.cn/v2/guides/authorization/m2m-authz.html"
);
}
if (!options) {
throw new Error(
"请在调用本方法时传入 { accessKey: string, accessSecret: string },请看文档:https://docs.authing.cn/v2/guides/authorization/m2m-authz.html"
// '请在初始化 AuthenticationClient 时传入 appId 和 secret 参数或者在调用本方法时传入 { accessKey: string, accessSecret: string },请看文档:https://docs.authing.cn/v2/guides/authorization/m2m-authz.html'
);
}
let i = options?.accessKey || this.options.appId;
let s = options?.accessSecret || this.options.appSecret;
const qstr = this._generateTokenRequest({
client_id: i,
client_secret: s,
grant_type: "client_credentials",
scope: scope,
});
let api = "";
if (this.options.protocol === "oidc") {
api = `/oidc/token`;
} else if (this.options.protocol === "oauth") {
api = `/oauth/token`;
}
let tokenSet = await this.httpClient.request({
method: "POST",
url: api,
data: qstr,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
return tokenSet;
}
/**
* 使用 Access token 获取用户信息。
*
* @param accessToken Access token,使用授权码 Code 换取的 Access token 的内容。
* @param options
* @returns
*/
public async getUserInfoByAccessToken(
accessToken: string,
options?: {
method?: "POST" | "GET";
tokenPlace?: "query" | "header" | "body";
}
) {
if (options) {
if (options.method && !["POST", "GET"].includes(options.method)) {
throw new Error("options.method 参数的可选值为 POST、GET,请检查输入");
}
if (
options.tokenPlace &&
!["query", "header", "body"].includes(options.tokenPlace)
) {
throw new Error(
"options.tokenPlace 参数的可选值为 query、header、body,请检查输入"
);
}
if (options.method === "GET" && options.tokenPlace === "body") {
throw new Error(
"options.method 参数为 GET 时,options.tokenPlace 参数不能为 body"
);
}
options.method = options.method || "GET";
options.tokenPlace = options.tokenPlace || "query";
}
let api = "";
if (this.options.protocol === "oidc") {
api = `/oidc/me`;
} else if (this.options.protocol === "oauth") {
api = `/oauth/me`;
}
if (options?.method === "POST") {
if (options?.tokenPlace === "header") {
let userInfo = await this.httpClient.request({
method: "POST",
url: api,
headers: {
Authorization: "Bearer " + accessToken,
},
});
return userInfo;
} else if (options?.tokenPlace === "query") {
let userInfo = await this.httpClient.request({
method: "POST",
url: api,
params: {
access_token: accessToken,
},
});
return userInfo;
} else if (options?.tokenPlace === "body") {
let userInfo = await this.httpClient.request({
method: "POST",
url: api,
data: serialize({
access_token: accessToken,
}),
});
return userInfo;
}
} else if (options?.method === "GET") {
if (options?.tokenPlace === "header") {
let userInfo = await this.httpClient.request({
method: "GET",
url: api,
headers: {
Authorization: "Bearer " + accessToken,
},
});
return userInfo;
} else if (options?.tokenPlace === "query") {
let userInfo = await this.httpClient.request({
method: "GET",
url: api,
params: {
access_token: accessToken,
},
});
return userInfo;
}
} else {
// 默认使用 GET + query 获取用户信息
let userInfo = await this.httpClient.request({
method: "GET",
url: api,
params: {
access_token: accessToken,
},
});
return userInfo;
}
}
/**
* 生成 OIDC/OAuth/CAS/SAML 协议的用户登录链接,用户可以通过此链接访问 Authing 的在线登录页面。
*
*/
public buildAuthorizeUrl(
options?: OidcParams | OauthParams | CasParams
): AuthUrlResult {
if (!this.options.appHost) {
throw new Error(
"请在初始化 AuthenticationClient 时传入应用域名 appHost 参数,形如:https://app1.authing.cn"
);
}
if (this.options.protocol === "oidc") {
return this._buildOidcAuthorizeUrl(options as OidcParams);
}
if (this.options.protocol === "oauth") {
const url = this._buildOauthAuthorizeUrl(options as OauthParams);
return {
url,
state: (options as OauthParams)?.state,
};
}
if (this.options.protocol === "saml") {
const url = this._buildSamlAuthorizeUrl();
return {
url,
state: (options as OauthParams)?.state,
};
}
if (this.options.protocol === "cas") {
const url = this._buildCasAuthorizeUrl(options as CasParams);
return {
url,
};
}
throw new Error(
"不支持的协议类型,请在初始化 AuthenticationClient 时传入 protocol 参数,可选值为 oidc、oauth、saml、cas"
);
}
private _buildOidcAuthorizeUrl(options?: OidcParams) {
const state = options?.state ?? generateRandomString(16);
const nonce = options?.nonce ?? generateRandomString(16);
const scope = options?.scope ?? this.options.scope;
const params: AuthURLParams = {
redirect_uri: options?.redirectUri ?? this.options.redirectUri,
response_mode: options?.responseMode || "query",
response_type: options?.responseType || "code",
client_id: this.options.appId,
scope,
state,
nonce,
};
if (options?.tenantId) {
params.tenant_id = options?.tenantId;
}
if (options?.forced) {
params.prompt = "login";
} else if (scope.split(" ").includes("offline_access")) {
params.prompt = "consent";
}
return {
url: `${this.options.appHost}/oidc/auth?${createQueryParams(params)}`,
state,
nonce,
};
}
private _buildOauthAuthorizeUrl(options: OauthParams) {
let map: any = {
appId: "client_id",
scope: "scope",
state: "state",
responseType: "response_type",
redirectUri: "redirect_uri",
};
let res: any = {
state: Math.random().toString().slice(2),
scope: "user",
client_id: this.options.appId,
redirect_uri: this.options.redirectUri,
response_type: "code",
};
Object.keys(map).forEach((k) => {
if (options && (options as any)[k]) {
res[map[k]] = (options as any)[k];
}
});
let params = new URLSearchParams(res);
let authorizeUrl =
this.options.appHost + "/oauth/auth?" + params.toString();
return authorizeUrl;
}
private _buildSamlAuthorizeUrl() {
return this.options.appHost + "/api/v2/saml-idp/" + this.options.appId;
}
private _buildCasAuthorizeUrl(options: CasParams) {
if (options?.service) {
return `${this.options.appHost}/cas-idp/${this.options.appId}?service=${options?.service}`;
}
return `${this.options.appHost}/cas-idp/${this.options.appId}`;
}
private _buildCasLogoutUrl(options: LogoutParams) {
if (options?.redirectUri) {
return (
this.options.appHost + "/cas-idp/logout?url=" + options.redirectUri
);
}
return `${this.options.appHost}/cas-idp/logout`;
}
private _buildOidcLogoutUrl(options: LogoutParams): string {
const redirectUri = options.redirectUri ?? this.options.logoutRedirectUri;
const params: LogoutURLParams = {
...(redirectUri && {
post_logout_redirect_uri: redirectUri,
state: options.state,
}),
id_token_hint: options.idToken,
};
return `${this.options.appHost}/oidc/session/end?${createQueryParams(
params
)}`;
}
private _buildEasyLogoutUrl(options?: LogoutParams) {
if (options?.redirectUri) {
return `${this.options.appHost}/login/profile/logout?redirect_uri=${options.redirectUri}`;
}
return `${this.options.appHost}/login/profile/logout`;
}
/**
* 拼接 CAS/OIDC 协议的登出 URL
*
*/
public buildLogoutUrl(options?: LogoutParams) {
if (this.options.protocol === "cas") {
return this._buildCasLogoutUrl(options!);
}
if (this.options.protocol === "oidc") {
return this._buildOidcLogoutUrl(options!);
} else {
throw this._buildEasyLogoutUrl(options!);
}
}
private async _getNewAccessTokenByRefreshTokenWithClientSecretPost(
refreshToken: string
) {
const qstr = this._generateTokenRequest({
client_id: this.options.appId,
client_secret: this.options.appSecret,
grant_type: "refresh_token",
refresh_token: refreshToken,
});
let api = "";
if (this.options.protocol === "oidc") {
api = `/oidc/token`;
} else if (this.options.protocol === "oauth") {
api = `/oauth/token`;
}
let tokenSet = await this.httpClient.request({
method: "POST",
url: api,
data: qstr,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
return tokenSet;
}
private async _getNewAccessTokenByRefreshTokenWithClientSecretBasic(
refreshToken: string
) {
let api = "";
if (this.options.protocol === "oidc") {
api = `/oidc/token`;
} else if (this.options.protocol === "oauth") {
api = `/oauth/token`;
}
const qstr = this._generateTokenRequest({
grant_type: "refresh_token",
refresh_token: refreshToken,
});
let tokenSet = await this.httpClient.request({
data: qstr,
method: "POST",
url: api,
headers: {
Authorization: this._generateBasicAuthToken(),
},
});
return tokenSet;
}
private async _getNewAccessTokenByRefreshTokenWithNone(refreshToken: string) {
let api = "";
if (this.options.protocol === "oidc") {
api = `${this.options.appHost}/oidc/token`;
} else if (this.options.protocol === "oauth") {
api = `${this.options.appHost}/oauth/token`;
}
const qstr = this._generateTokenRequest({
client_id: this.options.appId,
grant_type: "refresh_token",
refresh_token: refreshToken,
});
let tokenSet = await this.httpClient.request({
method: "POST",
url: api,
data: qstr,
});
return tokenSet;
}
/**
* 使用 Refresh token 获取新的 Access token。
* @param refreshToken Refresh token,可以从 AuthenticationClient.getAccessTokenByCode 方法的返回值中的 refresh_token 获得。
* @returns
*/
public async getNewAccessTokenByRefreshToken(refreshToken: string) {
if (!["oauth", "oidc"].includes(this.options.protocol)) {
throw new Error(
"初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc,请检查参数"
);
}
if (
!this.options.appSecret &&
this.options.tokenEndPointAuthMethod !== "none"
) {
throw new Error(
"请在初始化 AuthenticationClient 时传入 appId 和 secret 参数"
);
}
if (this.options.tokenEndPointAuthMethod === "client_secret_post") {
return await this._getNewAccessTokenByRefreshTokenWithClientSecretPost(
refreshToken
);
}
if (this.options.tokenEndPointAuthMethod === "client_secret_basic") {
return await this._getNewAccessTokenByRefreshTokenWithClientSecretBasic(
refreshToken
);
}
if (this.options.tokenEndPointAuthMethod === "none") {
return await this._getNewAccessTokenByRefreshTokenWithNone(refreshToken);
}
}
private async _revokeTokenWithClientSecretPost(token: string) {
const qstr = this._generateTokenRequest({
client_id: this.options.appId,
client_secret: this.options.appSecret,
token,
});
let api = "";
if (this.options.protocol === "oidc") {
api = `/oidc/token/revocation`;
} else if (this.options.protocol === "oauth") {
api = `/oauth/token/revocation`;
}
let tokenSet = await this.httpClient.request({
method: "POST",
url: api,
data: qstr,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
return tokenSet;
}
private async _revokeTokenWithClientSecretBasic(token: string) {
let api = "";
if (this.options.protocol === "oidc") {
api = `/oidc/token/revocation`;
} else if (this.options.protocol === "oauth") {
throw new Error(
"OAuth 2.0 暂不支持用 client_secret_basic 模式身份验证撤回 Token"
);
}
const qstr = this._generateTokenRequest({
token: token,
});
let result = await this.httpClient.request({
data: qstr,
method: "POST",
url: api,
headers: {
Authorization: this._generateBasicAuthToken(),
},
});
return result;
}
private async _revokeTokenWithNone(token: string) {
let api = "";
if (this.options.protocol === "oidc") {
api = `/oidc/token/revocation`;
} else if (this.options.protocol === "oauth") {
api = `/oauth/token/revocation`;
}
const qstr = this._generateTokenRequest({
client_id: this.options.appId,
token: token,
});
let result = await this.httpClient.request({
method: "POST",
url: api,
data: qstr,
});
return result;
}
/**
* 撤回 Access token 或 Refresh token。Access token 或 Refresh token 的持有者可以通知 Authing 已经不再需要令牌,希望 Authing 将其吊销。
* @param token Access token 或 Refresh token,可以从 AuthenticationClient.getAccessTokenByCode 方法的返回值中的 access_token、refresh_token 获得。
* @returns
*/
public async revokeToken(token: string) {
if (!["oauth", "oidc"].includes(this.options.protocol)) {
throw new Error(
"初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc,请检查参数"
);
}
if (
!this.options.appSecret &&
this.options.revocationEndPointAuthMethod !== "none"
) {
throw new Error(
"请在初始化 AuthenticationClient 时传入 appId 和 secret 参数"
);
}
if (this.options.revocationEndPointAuthMethod === "client_secret_post") {