-
Notifications
You must be signed in to change notification settings - Fork 49
/
CognitoUserAuthentication.cs
697 lines (598 loc) · 35.6 KB
/
CognitoUserAuthentication.cs
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
/*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/* The following knowledge base was used as guide for the implementation
* of some of the below Cognito challenges.
* https://aws.amazon.com/premiumsupport/knowledge-center/cognito-user-pool-remembered-devices/?nc1=h_ls
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.Threading.Tasks;
using Amazon.CognitoIdentity;
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
using Amazon.Extensions.CognitoAuthentication.Util;
namespace Amazon.Extensions.CognitoAuthentication
{
partial class CognitoUser
{
/// <summary>
/// Initiates the asynchronous SRP authentication flow
/// </summary>
/// <param name="srpRequest">InitiateSrpAuthRequest object containing the necessary parameters to
/// create an InitiateAuthAsync API call for SRP authentication</param>
/// <returns>Returns the AuthFlowResponse object that can be used to respond to the next challenge,
/// if one exists</returns>
public virtual async Task<AuthFlowResponse> StartWithSrpAuthAsync(InitiateSrpAuthRequest srpRequest)
{
if (srpRequest == null || string.IsNullOrEmpty(srpRequest.Password))
{
throw new ArgumentNullException("Password required for authentication.", "srpRequest");
}
Tuple<BigInteger, BigInteger> tupleAa = AuthenticationHelper.CreateAaTuple();
InitiateAuthRequest initiateRequest = CreateSrpAuthRequest(tupleAa);
InitiateAuthResponse initiateResponse = await Provider.InitiateAuthAsync(initiateRequest).ConfigureAwait(false);
UpdateUsernameAndSecretHash(initiateResponse.ChallengeParameters);
RespondToAuthChallengeRequest challengeRequest =
CreateSrpPasswordVerifierAuthRequest(initiateResponse, srpRequest.Password, tupleAa);
bool challengeResponsesValid = challengeRequest != null && challengeRequest.ChallengeResponses != null;
bool deviceKeyValid = Device != null && !string.IsNullOrEmpty(Device.DeviceKey);
if (challengeResponsesValid && deviceKeyValid)
{
challengeRequest.ChallengeResponses[CognitoConstants.ChlgParamDeviceKey] = Device.DeviceKey;
}
RespondToAuthChallengeResponse verifierResponse =
await Provider.RespondToAuthChallengeAsync(challengeRequest).ConfigureAwait(false);
var isDeviceAuthRequest = verifierResponse.AuthenticationResult == null && (!string.IsNullOrEmpty(srpRequest.DeviceGroupKey)
|| !string.IsNullOrEmpty(srpRequest.DevicePass));
#region Device-level authentication
if (isDeviceAuthRequest)
{
if (string.IsNullOrEmpty(srpRequest.DeviceGroupKey) || string.IsNullOrEmpty(srpRequest.DevicePass))
{
throw new ArgumentNullException("Device Group Key and Device Pass required for authentication.", "srpRequest");
}
#region Device SRP Auth
var deviceAuthRequest = CreateDeviceSrpAuthRequest(verifierResponse, tupleAa);
var deviceAuthResponse = await Provider.RespondToAuthChallengeAsync(deviceAuthRequest).ConfigureAwait(false);
#endregion
#region Device Password Verifier
var devicePasswordChallengeRequest = CreateDevicePasswordVerifierAuthRequest(deviceAuthResponse, srpRequest.DeviceGroupKey, srpRequest.DevicePass, tupleAa);
verifierResponse = await Provider.RespondToAuthChallengeAsync(devicePasswordChallengeRequest).ConfigureAwait(false);
#endregion
}
#endregion
UpdateSessionIfAuthenticationComplete(verifierResponse.ChallengeName, verifierResponse.AuthenticationResult);
return new AuthFlowResponse(verifierResponse.Session,
verifierResponse.AuthenticationResult,
verifierResponse.ChallengeName,
verifierResponse.ChallengeParameters,
new Dictionary<string, string>(verifierResponse.ResponseMetadata.Metadata));
}
/// <summary>
/// Internal method which responds to the DEVICE_SRP_AUTH challenge in SRP authentication
/// </summary>
/// <param name="challenge">The response from the PASSWORD_VERIFIER challenge</param>
/// <param name="tupleAa">Tuple of BigIntegers containing the A,a pair for the SRP protocol flow</param>
/// <returns></returns>
private RespondToAuthChallengeRequest CreateDeviceSrpAuthRequest(RespondToAuthChallengeResponse challenge, Tuple<BigInteger, BigInteger> tupleAa)
{
RespondToAuthChallengeRequest authChallengeRequest = new RespondToAuthChallengeRequest()
{
ChallengeName = "DEVICE_SRP_AUTH",
ClientId = ClientID,
Session = challenge.Session,
ChallengeResponses = new Dictionary<string, string>
{
{CognitoConstants.ChlgParamUsername, Username},
{CognitoConstants.ChlgParamDeviceKey, Device.DeviceKey},
{CognitoConstants.ChlgParamSrpA, tupleAa.Item1.ToString("X") },
}
};
if (!string.IsNullOrEmpty(ClientSecret))
{
SecretHash = CognitoAuthHelper.GetUserPoolSecretHash(Username, ClientID, ClientSecret);
authChallengeRequest.ChallengeResponses.Add(CognitoConstants.ChlgParamSecretHash, SecretHash);
}
return authChallengeRequest;
}
/// <summary>
/// Internal method which responds to the DEVICE_PASSWORD_VERIFIER challenge in SRP authentication
/// </summary>
/// <param name="challenge">Response from the InitiateAuth challenge</param>
/// <param name="deviceKeyGroup">Group Key for the CognitoDevice, needed for authentication</param>
/// <param name="devicePassword">Password for the CognitoDevice, needed for authentication</param>
/// <param name="tupleAa">Tuple of BigIntegers containing the A,a pair for the SRP protocol flow</param>
/// <returns>Returns the RespondToAuthChallengeRequest for an SRP authentication flow</returns>
private RespondToAuthChallengeRequest CreateDevicePasswordVerifierAuthRequest(RespondToAuthChallengeResponse challenge,
string deviceKeyGroup,
string devicePassword,
Tuple<BigInteger, BigInteger> tupleAa)
{
string deviceKey = challenge.ChallengeParameters[CognitoConstants.ChlgParamDeviceKey];
string username = challenge.ChallengeParameters[CognitoConstants.ChlgParamUsername];
string secretBlock = challenge.ChallengeParameters[CognitoConstants.ChlgParamSecretBlock];
string salt = challenge.ChallengeParameters[CognitoConstants.ChlgParamSalt];
BigInteger srpb = BigIntegerExtensions.FromUnsignedLittleEndianHex(challenge.ChallengeParameters[CognitoConstants.ChlgParamSrpB]);
if ((srpb.TrueMod(AuthenticationHelper.N)).Equals(BigInteger.Zero))
{
throw new ArgumentException("SRP error, B mod N cannot be zero.", "challenge");
}
string timeStr = DateTime.UtcNow.ToString("ddd MMM d HH:mm:ss \"UTC\" yyyy", CultureInfo.InvariantCulture);
var claimBytes = AuthenticationHelper.AuthenticateDevice(username, deviceKey, devicePassword, deviceKeyGroup, salt,
challenge.ChallengeParameters[CognitoConstants.ChlgParamSrpB], secretBlock, timeStr, tupleAa);
string claimB64 = Convert.ToBase64String(claimBytes);
Dictionary<string, string> srpAuthResponses = new Dictionary<string, string>(StringComparer.Ordinal)
{
{CognitoConstants.ChlgParamPassSecretBlock, secretBlock},
{CognitoConstants.ChlgParamPassSignature, claimB64},
{CognitoConstants.ChlgParamUsername, username },
{CognitoConstants.ChlgParamTimestamp, timeStr },
{CognitoConstants.ChlgParamDeviceKey, Device.DeviceKey }
};
if (!string.IsNullOrEmpty(ClientSecret))
{
SecretHash = CognitoAuthHelper.GetUserPoolSecretHash(Username, ClientID, ClientSecret);
srpAuthResponses.Add(CognitoConstants.ChlgParamSecretHash, SecretHash);
}
RespondToAuthChallengeRequest authChallengeRequest = new RespondToAuthChallengeRequest()
{
ChallengeName = challenge.ChallengeName,
ClientId = ClientID,
Session = challenge.Session,
ChallengeResponses = srpAuthResponses
};
return authChallengeRequest;
}
/// <summary>
/// Initiates the asynchronous custom authentication flow
/// </summary>
/// <param name="customRequest">InitiateCustomAuthRequest object containing the necessary parameters to
/// create an InitiateAuthAsync API call for custom authentication</param>
/// <returns>Returns the AuthFlowResponse object that can be used to respond to the next challenge,
/// if one exists</returns>
public virtual async Task<AuthFlowResponse> StartWithCustomAuthAsync(InitiateCustomAuthRequest customRequest)
{
InitiateAuthRequest authRequest = new InitiateAuthRequest()
{
AuthFlow = AuthFlowType.CUSTOM_AUTH,
AuthParameters = new Dictionary<string, string>(customRequest.AuthParameters),
ClientId = ClientID,
ClientMetadata = new Dictionary<string, string>(customRequest.ClientMetadata)
};
InitiateAuthResponse initiateResponse = await Provider.InitiateAuthAsync(authRequest).ConfigureAwait(false);
UpdateUsernameAndSecretHash(initiateResponse.ChallengeParameters);
UpdateSessionIfAuthenticationComplete(initiateResponse.ChallengeName, initiateResponse.AuthenticationResult);
return new AuthFlowResponse(initiateResponse.Session,
initiateResponse.AuthenticationResult,
initiateResponse.ChallengeName,
initiateResponse.ChallengeParameters,
new Dictionary<string, string>(initiateResponse.ResponseMetadata.Metadata));
}
/// <summary>
/// Uses the properties of the RespondToCustomChallengeRequest object to respond to the current
/// custom authentication challenge using an asynchronous call
/// </summary>
/// <param name="customRequest">RespondToCustomChallengeRequest object containing the necessary parameters to
/// respond to the current custom authentication challenge</param>
/// <returns>Returns the AuthFlowResponse object that can be used to respond to the next challenge,
/// if one exists</returns>
public virtual async Task<AuthFlowResponse> RespondToCustomAuthAsync(RespondToCustomChallengeRequest customRequest)
{
RespondToAuthChallengeRequest request = new RespondToAuthChallengeRequest()
{
ChallengeName = ChallengeNameType.CUSTOM_CHALLENGE,
ClientId = ClientID,
ChallengeResponses = new Dictionary<string, string>(customRequest.ChallengeParameters),
Session = customRequest.SessionID
};
RespondToAuthChallengeResponse authResponse =
await Provider.RespondToAuthChallengeAsync(request).ConfigureAwait(false);
UpdateSessionIfAuthenticationComplete(authResponse.ChallengeName, authResponse.AuthenticationResult);
return new AuthFlowResponse(authResponse.Session,
authResponse.AuthenticationResult,
authResponse.ChallengeName,
authResponse.ChallengeParameters,
new Dictionary<string, string>(authResponse.ResponseMetadata.Metadata));
}
/// <summary>
/// Generates a DeviceSecretVerifierConfigType object for a device associated with a CognitoUser for SRP Authentication
/// </summary>
/// <param name="deviceGroupKey">The DeviceKey Group for the associated CognitoDevice</param>
/// <param name="deviceKey">The DeviceKey for the associated CognitoDevice</param>
/// <param name="devicePass">The random password for the associated CognitoDevice</param>
/// <returns></returns>
public DeviceSecretVerifierConfigType GenerateDeviceVerifier(string deviceGroupKey, string devicePass, string username)
{
return AuthenticationHelper.GenerateDeviceVerifier(deviceGroupKey, devicePass, username);
}
/// <summary>
/// Sends a confirmation request to Cognito for a new CognitoDevice
/// </summary>
/// <param name="accessToken">The user pool access token for from the InitiateAuth or other challenge response</param>
/// <param name="deviceKey">The device key for the associated CognitoDevice</param>
/// <param name="deviceName">The friendly name to be associated with the corresponding CognitoDevice</param>
/// <param name="passwordVerifier">The password verifier generated from GenerateDeviceVerifier for the corresponding CognitoDevice</param>
/// <param name="salt">The salt generated from GenerateDeviceVerifier for the corresponding CognitoDevice</param>
/// <returns></returns>
public async Task<ConfirmDeviceResponse> ConfirmDeviceAsync(string accessToken, string deviceKey, string deviceName, string passwordVerifier, string salt)
{
var request = new ConfirmDeviceRequest
{
AccessToken = accessToken,
DeviceKey = deviceKey,
DeviceName = deviceName,
DeviceSecretVerifierConfig = new DeviceSecretVerifierConfigType
{
PasswordVerifier = passwordVerifier,
Salt = salt
}
};
return await Provider.ConfirmDeviceAsync(request);
}
/// <summary>
/// Updates the remembered status for a given CognitoDevice
/// </summary>
/// <param name="accessToken">The user pool access token for from the InitiateAuth or other challenge response</param>
/// <param name="deviceKey">The device key for the associated CognitoDevice</param>
/// <param name="deviceRememberedStatus">The device remembered status for the associated CognitoDevice</param>
/// <returns></returns>
public async Task<UpdateDeviceStatusResponse> UpdateDeviceStatusAsync(string accessToken, string deviceKey, string deviceRememberedStatus)
{
var request = new UpdateDeviceStatusRequest
{
AccessToken = accessToken,
DeviceKey = deviceKey,
DeviceRememberedStatus = deviceRememberedStatus
};
return await Provider.UpdateDeviceStatusAsync(request);
}
/// <summary>
/// Uses the properties of the RespondToSmsMfaRequest object to respond to the current MFA
/// authentication challenge using an asynchronous call
/// </summary>
/// <param name="smsMfaRequest">RespondToSmsMfaRequest object containing the necessary parameters to
/// respond to the current SMS MFA authentication challenge</param>
/// <returns>Returns the AuthFlowResponse object that can be used to respond to the next challenge,
/// if one exists</returns>
public virtual async Task<AuthFlowResponse> RespondToSmsMfaAuthAsync(RespondToSmsMfaRequest smsMfaRequest)
{
return await RespondToMfaAuthAsync(smsMfaRequest).ConfigureAwait(false);
}
/// <summary>
/// Uses the properties of the RespondToSmsMfaRequest object to respond to the current MFA
/// authentication challenge using an asynchronous call
/// </summary>
/// <param name="mfaRequest">RespondToMfaRequest object containing the necessary parameters to
/// respond to the current MFA authentication challenge</param>
/// <returns>Returns the AuthFlowResponse object that can be used to respond to the next challenge,
/// if one exists</returns>
public async Task<AuthFlowResponse> RespondToMfaAuthAsync(RespondToMfaRequest mfaRequest)
{
RespondToAuthChallengeRequest challengeRequest = new RespondToAuthChallengeRequest
{
ChallengeResponses = new Dictionary<string, string>
{
{ GetChallengeParamCodeName(mfaRequest.ChallengeNameType), mfaRequest.MfaCode},
{ CognitoConstants.ChlgParamUsername, Username }
},
Session = mfaRequest.SessionID,
ClientId = ClientID,
ChallengeName = mfaRequest.ChallengeNameType
};
if (!string.IsNullOrEmpty(SecretHash))
{
challengeRequest.ChallengeResponses.Add(CognitoConstants.ChlgParamSecretHash, SecretHash);
}
RespondToAuthChallengeResponse challengeResponse =
await Provider.RespondToAuthChallengeAsync(challengeRequest).ConfigureAwait(false);
UpdateSessionIfAuthenticationComplete(challengeResponse.ChallengeName, challengeResponse.AuthenticationResult);
return new AuthFlowResponse(challengeResponse.Session,
challengeResponse.AuthenticationResult,
challengeResponse.ChallengeName,
challengeResponse.ChallengeParameters,
new Dictionary<string, string>(challengeResponse.ResponseMetadata.Metadata));
}
/// <summary>
/// Internal method which works out which Challenge Parameter to use based on the ChallengeTypeName
/// </summary>
/// <param name="challengeNameType">ChallengeTypeName from the challenge</param>
/// <returns>Returns the CognitoConstants for the given ChallengeTypeName</returns>
private string GetChallengeParamCodeName(ChallengeNameType challengeNameType )
{
if (challengeNameType == ChallengeNameType.SMS_MFA) return CognitoConstants.ChlgParamSmsMfaCode;
if (challengeNameType == ChallengeNameType.SOFTWARE_TOKEN_MFA) return CognitoConstants.ChlgParamSoftwareTokenMfaCode;
return null;
}
/// <summary>
/// Uses the properties of the RespondToNewPasswordRequiredRequest object to respond to the current new
/// password required authentication challenge using an asynchronous call
/// </summary>
/// <param name="newPasswordRequest">RespondToNewPasswordRequiredRequest object containing the necessary
/// parameters to respond to the current SMS MFA authentication challenge</param>
/// <returns>Returns the AuthFlowResponse object that can be used to respond to the next challenge,
/// if one exists</returns>
public virtual Task<AuthFlowResponse> RespondToNewPasswordRequiredAsync(RespondToNewPasswordRequiredRequest newPasswordRequest)
{
return RespondToNewPasswordRequiredAsync(newPasswordRequest, null);
}
/// <summary>
/// Uses the properties of the RespondToNewPasswordRequiredRequest object to respond to the current new
/// password required authentication challenge using an asynchronous call
/// </summary>
/// <param name="newPasswordRequest">RespondToNewPasswordRequiredRequest object containing the necessary
/// <param name="requiredAttributes">Optional dictionnary of attributes that may be required by the user pool
/// Each attribute key must be prefixed by "userAttributes."
/// parameters to respond to the current SMS MFA authentication challenge</param>
/// <returns>Returns the AuthFlowResponse object that can be used to respond to the next challenge,
/// if one exists</returns>
public virtual async Task<AuthFlowResponse> RespondToNewPasswordRequiredAsync(RespondToNewPasswordRequiredRequest newPasswordRequest, Dictionary<string, string> requiredAttributes)
{
var challengeResponses = new Dictionary<string, string>()
{
{ CognitoConstants.ChlgParamNewPassword, newPasswordRequest.NewPassword},
{ CognitoConstants.ChlgParamUsername, Username }
};
if (requiredAttributes != null)
{
foreach (KeyValuePair<string, string> attribute in requiredAttributes)
{
challengeResponses.Add(attribute.Key, attribute.Value);
}
}
RespondToAuthChallengeRequest challengeRequest = new RespondToAuthChallengeRequest
{
ChallengeResponses = challengeResponses,
Session = newPasswordRequest.SessionID,
ClientId = ClientID,
ChallengeName = ChallengeNameType.NEW_PASSWORD_REQUIRED
};
if (!string.IsNullOrEmpty(SecretHash))
{
challengeRequest.ChallengeResponses.Add(CognitoConstants.ChlgParamSecretHash, SecretHash);
}
RespondToAuthChallengeResponse challengeResponse =
await Provider.RespondToAuthChallengeAsync(challengeRequest).ConfigureAwait(false);
UpdateSessionIfAuthenticationComplete(challengeResponse.ChallengeName, challengeResponse.AuthenticationResult);
return new AuthFlowResponse(challengeResponse.Session,
challengeResponse.AuthenticationResult,
challengeResponse.ChallengeName,
challengeResponse.ChallengeParameters,
new Dictionary<string, string>(challengeResponse.ResponseMetadata.Metadata));
}
/// <summary>
/// Initiates the asynchronous refresh token authentication flow
/// </summary>
/// <param name="refreshTokenRequest">InitiateRefreshTokenAuthRequest object containing the necessary
/// parameters to initiate the refresh token authentication flow</param>
/// <returns>Returns the AuthFlowResponse object that can be used to respond to the next challenge,
/// if one exists</returns>
public virtual async Task<AuthFlowResponse> StartWithRefreshTokenAuthAsync(InitiateRefreshTokenAuthRequest refreshTokenRequest)
{
InitiateAuthRequest initiateAuthRequest = CreateRefreshTokenAuthRequest(refreshTokenRequest.AuthFlowType);
InitiateAuthResponse initiateResponse =
await Provider.InitiateAuthAsync(initiateAuthRequest).ConfigureAwait(false);
// Service does not return the refresh token. Hence, set it to the old refresh token that was used.
if (string.IsNullOrEmpty(initiateResponse.ChallengeName) && string.IsNullOrEmpty(initiateResponse.AuthenticationResult.RefreshToken))
initiateResponse.AuthenticationResult.RefreshToken = initiateAuthRequest.AuthParameters[CognitoConstants.ChlgParamRefreshToken];
UpdateSessionIfAuthenticationComplete(initiateResponse.ChallengeName, initiateResponse.AuthenticationResult);
return new AuthFlowResponse(initiateResponse.Session,
initiateResponse.AuthenticationResult,
initiateResponse.ChallengeName,
initiateResponse.ChallengeParameters,
new Dictionary<string, string>(initiateResponse.ResponseMetadata.Metadata));
}
/// <summary>
/// Initiates the asynchronous ADMIN_NO_SRP_AUTH authentication flow
/// </summary>
/// <param name="adminAuthRequest">InitiateAdminNoSrpAuthRequest object containing the necessary
/// parameters to initiate the ADMIN_NO_SRP_AUTH authentication flow</param>
/// <returns>Returns the AuthFlowResponse object that can be used to respond to the next challenge,
/// if one exists</returns>
public virtual async Task<AuthFlowResponse> StartWithAdminNoSrpAuthAsync(InitiateAdminNoSrpAuthRequest adminAuthRequest)
{
AdminInitiateAuthRequest initiateAuthRequest = CreateAdminAuthRequest(adminAuthRequest);
AdminInitiateAuthResponse initiateResponse =
await Provider.AdminInitiateAuthAsync(initiateAuthRequest).ConfigureAwait(false);
UpdateSessionIfAuthenticationComplete(initiateResponse.ChallengeName, initiateResponse.AuthenticationResult);
return new AuthFlowResponse(initiateResponse.Session,
initiateResponse.AuthenticationResult,
initiateResponse.ChallengeName,
initiateResponse.ChallengeParameters,
new Dictionary<string, string>(initiateResponse.ResponseMetadata.Metadata));
}
/// <summary>
/// Internal method for updating the CognitoUser SessionTokens property if properly authenticated
/// </summary>
private void UpdateSessionIfAuthenticationComplete(ChallengeNameType challengeName, AuthenticationResultType authResult)
{
if (string.IsNullOrEmpty(challengeName))
{
CognitoUserSession cognitoUserSession = GetCognitoUserSession(authResult);
this.SessionTokens = cognitoUserSession;
}
}
/// <summary>
/// Interal method which creates the InitiateAuthRequest for an SRP authentication flow
/// </summary>
/// <param name="tupleAa">Tuple containing the A,a pair for SRP authentication</param>
/// <returns>Returns the InitiateAuthRequest for an SRP authentication flow</returns>
private InitiateAuthRequest CreateSrpAuthRequest(Tuple<BigInteger, BigInteger> tupleAa)
{
InitiateAuthRequest initiateAuthRequest = new InitiateAuthRequest()
{
AuthFlow = AuthFlowType.USER_SRP_AUTH,
ClientId = ClientID,
AuthParameters = new Dictionary<string, string>(StringComparer.Ordinal)
{
{ CognitoConstants.ChlgParamUsername, Username },
{ CognitoConstants.ChlgParamSrpA, tupleAa.Item1.ToString("X") }
}
};
if (!string.IsNullOrEmpty(ClientSecret))
{
initiateAuthRequest.AuthParameters.Add(CognitoConstants.ChlgParamSecretHash,
CognitoAuthHelper.GetUserPoolSecretHash(Username, ClientID, ClientSecret));
}
if (Device != null && !string.IsNullOrEmpty(Device.DeviceKey))
{
initiateAuthRequest.AuthParameters.Add(CognitoConstants.ChlgParamDeviceKey, Device.DeviceKey);
}
return initiateAuthRequest;
}
/// <summary>
/// Internal mehtod which updates CognitoUser's username, secret hash, and device key from challege parameters
/// </summary>
/// <param name="challengeParameters">Dictionary containing the key-value pairs for challenge parameters</param>
private void UpdateUsernameAndSecretHash(IDictionary<string, string> challengeParameters)
{
bool canSetUsername = string.IsNullOrEmpty(Username) || string.Equals(UserID, Username, StringComparison.Ordinal);
bool challengeParamIsUsername = challengeParameters != null && challengeParameters.ContainsKey(CognitoConstants.ChlgParamUsername);
bool shouldUpdate = canSetUsername || challengeParamIsUsername;
if (!shouldUpdate)
{
return;
}
if (challengeParameters.ContainsKey(CognitoConstants.ChlgParamUsername))
{
Username = challengeParameters[CognitoConstants.ChlgParamUsername];
}
if (!string.IsNullOrEmpty(ClientSecret))
{
SecretHash = CognitoAuthHelper.GetUserPoolSecretHash(Username, ClientID, ClientSecret);
}
}
private AdminInitiateAuthRequest CreateAdminAuthRequest(InitiateAdminNoSrpAuthRequest adminRequest)
{
AdminInitiateAuthRequest returnRequest = new AdminInitiateAuthRequest()
{
AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH,
ClientId = ClientID,
UserPoolId = UserPool.PoolID,
AuthParameters = new Dictionary<string, string>()
{
{ CognitoConstants.ChlgParamUsername, Username },
{CognitoConstants.ChlgParamPassword, adminRequest.Password }
}
};
if (Device != null && !string.IsNullOrEmpty(Device.DeviceKey))
{
returnRequest.AuthParameters.Add(CognitoConstants.ChlgParamDeviceKey, Device.DeviceKey);
}
if (!string.IsNullOrEmpty(SecretHash))
{
returnRequest.AuthParameters.Add(CognitoConstants.ChlgParamSecretHash, SecretHash);
}
if (adminRequest.ClientMetadata != null)
{
returnRequest.ClientMetadata = new Dictionary<string, string>(adminRequest.ClientMetadata);
}
return returnRequest;
}
private InitiateAuthRequest CreateRefreshTokenAuthRequest(AuthFlowType authFlowType)
{
EnsureUserAuthenticated();
if (authFlowType != AuthFlowType.REFRESH_TOKEN && authFlowType != AuthFlowType.REFRESH_TOKEN_AUTH)
{
throw new ArgumentException("authFlowType must be either \"REFRESH_TOKEN\" or \"REFRESH_TOKEN_AUTH\"", "authFlowType");
}
InitiateAuthRequest initiateAuthRequest = new InitiateAuthRequest()
{
AuthFlow = authFlowType,
ClientId = ClientID,
AuthParameters = new Dictionary<string, string>()
{
{CognitoConstants.ChlgParamUsername, Username },
{CognitoConstants.ChlgParamRefreshToken, SessionTokens.RefreshToken }
}
};
if (Device != null && !string.IsNullOrEmpty(Device.DeviceKey))
{
initiateAuthRequest.AuthParameters.Add(CognitoConstants.ChlgParamDeviceKey, Device.DeviceKey);
}
if (!string.IsNullOrEmpty(SecretHash))
{
initiateAuthRequest.AuthParameters.Add(CognitoConstants.ChlgParamSecretHash, SecretHash);
}
return initiateAuthRequest;
}
/// <summary>
/// Internal method which responds to the PASSWORD_VERIFIER challenge in SRP authentication
/// </summary>
/// <param name="challenge">Response from the InitiateAuth challenge</param>
/// <param name="password">Password for the CognitoUser, needed for authentication</param>
/// <param name="tupleAa">Tuple of BigIntegers containing the A,a pair for the SRP protocol flow</param>
/// <returns>Returns the RespondToAuthChallengeRequest for an SRP authentication flow</returns>
private RespondToAuthChallengeRequest CreateSrpPasswordVerifierAuthRequest(InitiateAuthResponse challenge,
string password,
Tuple<BigInteger, BigInteger> tupleAa)
{
string username = challenge.ChallengeParameters[CognitoConstants.ChlgParamUsername];
string poolName = PoolName;
string secretBlock = challenge.ChallengeParameters[CognitoConstants.ChlgParamSecretBlock];
string salt = challenge.ChallengeParameters[CognitoConstants.ChlgParamSalt];
BigInteger srpb = BigIntegerExtensions.FromUnsignedLittleEndianHex(challenge.ChallengeParameters[CognitoConstants.ChlgParamSrpB]);
if ((srpb.TrueMod(AuthenticationHelper.N)).Equals(BigInteger.Zero))
{
throw new ArgumentException("SRP error, B mod N cannot be zero.", "challenge");
}
DateTime timestamp = DateTime.UtcNow;
string timeStr = timestamp.ToString("ddd MMM d HH:mm:ss \"UTC\" yyyy", CultureInfo.InvariantCulture);
byte[] claim = AuthenticationHelper.AuthenticateUser(username, password, poolName, tupleAa, salt,
challenge.ChallengeParameters[CognitoConstants.ChlgParamSrpB], secretBlock, timeStr);
string claimBase64 = Convert.ToBase64String(claim);
Dictionary<string, string> srpAuthResponses = new Dictionary<string, string>(StringComparer.Ordinal)
{
{CognitoConstants.ChlgParamPassSecretBlock, secretBlock},
{CognitoConstants.ChlgParamPassSignature, claimBase64},
{CognitoConstants.ChlgParamUsername, username },
{CognitoConstants.ChlgParamTimestamp, timeStr },
};
if (!string.IsNullOrEmpty(ClientSecret))
{
SecretHash = CognitoAuthHelper.GetUserPoolSecretHash(Username, ClientID, ClientSecret);
srpAuthResponses.Add(CognitoConstants.ChlgParamSecretHash, SecretHash);
}
if (Device != null && !string.IsNullOrEmpty(Device.DeviceKey))
{
srpAuthResponses.Add(CognitoConstants.ChlgParamDeviceKey, Device.DeviceKey);
}
RespondToAuthChallengeRequest authChallengeRequest = new RespondToAuthChallengeRequest()
{
ChallengeName = challenge.ChallengeName,
ClientId = ClientID,
Session = challenge.Session,
ChallengeResponses = srpAuthResponses
};
return authChallengeRequest;
}
/// <summary>
/// Creates the CognitoAWSCredentials for accessing AWS resources. Should only be called with an authenticated user.
/// </summary>
/// <param name="identityPoolID">The poolID of the identity pool the user belongs to</param>
/// <param name="identityPoolRegion">The region of the identity pool the user belongs to</param>
/// <returns>Returns the CognitoAWSCredentials for the user to be able to access AWS resources</returns>
public CognitoAWSCredentials GetCognitoAWSCredentials(string identityPoolID, RegionEndpoint identityPoolRegion)
{
EnsureUserAuthenticated();
string poolRegion = UserPool.PoolID.Substring(0, UserPool.PoolID.IndexOf("_"));
string providerName = "cognito-idp." + poolRegion + ".amazonaws.com/" + UserPool.PoolID;
CognitoAWSCredentials credentials = new CognitoAWSCredentials(identityPoolID, identityPoolRegion);
credentials.AddLogin(providerName, SessionTokens.IdToken);
return credentials;
}
}
}