-
Notifications
You must be signed in to change notification settings - Fork 886
/
AWSCognitoIdentityUser.m
1914 lines (1635 loc) · 110 KB
/
AWSCognitoIdentityUser.m
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
//
// Copyright 2014-2018 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
#import "AWSCognitoIdentityProvider.h"
#import "AWSCognitoIdentityUser_Internal.h"
#import "AWSCognitoIdentityUserPool_Internal.h"
#import "AWSCognitoIdentityProviderSrpHelper.h"
#import "AWSJKBigInteger.h"
#import "NSData+AWSCognitoIdentityProvider.h"
#import <CommonCrypto/CommonDigest.h>
@interface AWSCognitoIdentityUserPool()
@property (nonatomic, strong) AWSCognitoIdentityProvider *client;
@property (nonatomic, assign) BOOL isCustomAuth;
@end
@implementation AWSCognitoIdentityUser
static const NSString * AWSCognitoIdentityUserDerivedKeyInfo = @"Caldera Derived Key";
static const NSString * AWSCognitoIdentityUserAccessToken = @"accessToken";
static const NSString * AWSCognitoIdentityUserIdToken = @"idToken";
static const NSString * AWSCognitoIdentityUserRefreshToken = @"refreshToken";
static const NSString * AWSCognitoIdentityUserTokenExpiration = @"tokenExpiration";
static const NSString * AWSCognitoIdentityUserDeviceId = @"device.id";
static const NSString * AWSCognitoIdentityUserAsfDeviceId = @"asf.device.id";
static const NSString * AWSCognitoIdentityUserDeviceSecret = @"device.secret";
static const NSString * AWSCognitoIdentityUserDeviceGroup = @"device.group";
static const NSString * AWSCognitoIdentityUserUserAttributePrefix = @"userAttributes.";
-(instancetype) initWithUsername: (NSString *)username pool:(AWSCognitoIdentityUserPool *)pool {
self = [super init];
if(self != nil) {
_username = username;
_pool = pool;
_confirmedStatus = AWSCognitoIdentityUserStatusUnknown;
}
return self;
}
-(AWSTask<AWSCognitoIdentityUserConfirmSignUpResponse *> *) confirmSignUp:(NSString *) confirmationCode
forceAliasCreation:(BOOL)forceAliasCreation
clientMetaData:(nullable NSDictionary<NSString *,NSString *> *)clientMetaData {
AWSCognitoIdentityProviderConfirmSignUpRequest *request = [AWSCognitoIdentityProviderConfirmSignUpRequest new];
request.clientId = self.pool.userPoolConfiguration.clientId;
request.username = self.username;
request.secretHash = [self.pool calculateSecretHash:self.username];
request.confirmationCode = confirmationCode;
request.forceAliasCreation = (forceAliasCreation?@(YES):@(NO));
request.analyticsMetadata = [self.pool analyticsMetadata];
request.userContextData = [self.pool userContextData:self.username deviceId: [self asfDeviceId]];
request.clientMetadata = clientMetaData;
return [[self.pool.client confirmSignUp:request] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderConfirmSignUpResponse *> * _Nonnull task) {
if (task.error) {
self.confirmedStatus = AWSCognitoIdentityUserStatusUnconfirmed;
return task;
} else {
self.confirmedStatus = AWSCognitoIdentityUserStatusConfirmed;
AWSCognitoIdentityUserConfirmSignUpResponse * response = [AWSCognitoIdentityUserConfirmSignUpResponse new];
[response aws_copyPropertiesFromObject:task.result];
return [AWSTask taskWithResult:response];
}
}];
}
-(AWSTask<AWSCognitoIdentityUserConfirmSignUpResponse *> *) confirmSignUp:(NSString *) confirmationCode
forceAliasCreation:(BOOL)forceAliasCreation {
return [self confirmSignUp:confirmationCode forceAliasCreation:forceAliasCreation clientMetaData:nil];
}
-(AWSTask<AWSCognitoIdentityUserConfirmSignUpResponse *> *) confirmSignUp:(NSString *) confirmationCode
clientMetaData:(nullable NSDictionary<NSString *,NSString *> *)clientMetaData {
return [self confirmSignUp:confirmationCode forceAliasCreation:NO clientMetaData:clientMetaData];
}
-(AWSTask<AWSCognitoIdentityUserConfirmSignUpResponse *> *) confirmSignUp:(NSString *) confirmationCode {
return [self confirmSignUp:confirmationCode forceAliasCreation:NO clientMetaData:nil];
}
-(AWSTask<AWSCognitoIdentityUserForgotPasswordResponse *> *) forgotPassword:(nullable NSDictionary<NSString *, NSString*> *) clientMetaData {
AWSCognitoIdentityProviderForgotPasswordRequest *request = [AWSCognitoIdentityProviderForgotPasswordRequest new];
request.clientId = self.pool.userPoolConfiguration.clientId;
request.username = self.username;
request.secretHash = [self.pool calculateSecretHash:self.username];
request.analyticsMetadata = [self.pool analyticsMetadata];
request.userContextData = [self.pool userContextData:self.username deviceId: [self asfDeviceId]];
request.clientMetadata = clientMetaData;
return [[self.pool.client forgotPassword:request] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderForgotPasswordResponse *> * _Nonnull task) {
AWSCognitoIdentityUserForgotPasswordResponse * response = [AWSCognitoIdentityUserForgotPasswordResponse new];
[response aws_copyPropertiesFromObject:task.result];
return [AWSTask taskWithResult:response];
}];
}
-(AWSTask<AWSCognitoIdentityUserForgotPasswordResponse *> *) forgotPassword {
return [self forgotPassword:nil];
}
-(AWSTask<AWSCognitoIdentityUserConfirmForgotPasswordResponse *> *) confirmForgotPassword: (NSString *)confirmationCode
password:(NSString *) password
clientMetaData:(nullable NSDictionary<NSString *,NSString *> *)clientMetaData {
AWSCognitoIdentityProviderConfirmForgotPasswordRequest *request = [AWSCognitoIdentityProviderConfirmForgotPasswordRequest new];
request.clientId = self.pool.userPoolConfiguration.clientId;
request.username = self.username;
request.secretHash = [self.pool calculateSecretHash:self.username];
request.password = password;
request.confirmationCode = confirmationCode;
request.analyticsMetadata = [self.pool analyticsMetadata];
request.userContextData = [self.pool userContextData:self.username deviceId: [self asfDeviceId]];
request.clientMetadata = clientMetaData;
return [[self.pool.client confirmForgotPassword:request] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderConfirmForgotPasswordResponse *> * _Nonnull task) {
AWSCognitoIdentityUserConfirmForgotPasswordResponse * response = [AWSCognitoIdentityUserConfirmForgotPasswordResponse new];
[response aws_copyPropertiesFromObject:task.result];
return [AWSTask taskWithResult:response];
}];
}
-(AWSTask<AWSCognitoIdentityUserConfirmForgotPasswordResponse *> *) confirmForgotPassword: (NSString *)confirmationCode
password:(NSString *) password {
return [self confirmForgotPassword:confirmationCode
password:password
clientMetaData:nil];
}
-(AWSTask<AWSCognitoIdentityUserResendConfirmationCodeResponse *> *) resendConfirmationCode: (nullable NSDictionary<NSString *,NSString *> *)clientMetaData {
AWSCognitoIdentityProviderResendConfirmationCodeRequest *request = [AWSCognitoIdentityProviderResendConfirmationCodeRequest new];
request.clientId = self.pool.userPoolConfiguration.clientId;
request.username = self.username;
request.secretHash = [self.pool calculateSecretHash:self.username];
request.analyticsMetadata = [self.pool analyticsMetadata];
request.userContextData = [self.pool userContextData:self.username deviceId: [self asfDeviceId]];
request.clientMetadata = clientMetaData;
return [[self.pool.client resendConfirmationCode:request] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderResendConfirmationCodeResponse *> * _Nonnull task) {
AWSCognitoIdentityUserResendConfirmationCodeResponse * response = [AWSCognitoIdentityUserResendConfirmationCodeResponse new];
[response aws_copyPropertiesFromObject:task.result];
return [AWSTask taskWithResult:response];
}];
}
-(AWSTask<AWSCognitoIdentityUserResendConfirmationCodeResponse *> *) resendConfirmationCode {
return [self resendConfirmationCode: nil];
}
-(AWSTask<AWSCognitoIdentityUserChangePasswordResponse *>*) changePassword: (NSString*)currentPassword proposedPassword: (NSString *)proposedPassword {
AWSCognitoIdentityProviderChangePasswordRequest* request = [AWSCognitoIdentityProviderChangePasswordRequest new];
request.previousPassword = currentPassword;
request.proposedPassword = proposedPassword;
return [[self getSession] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserSession *> * _Nonnull task) {
request.accessToken = task.result.accessToken.tokenString;
return [[self.pool.client changePassword:request] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderChangePasswordResponse *> * _Nonnull task) {
AWSCognitoIdentityProviderChangePasswordResponse * apiResponse = task.result;
AWSCognitoIdentityUserChangePasswordResponse *response = [AWSCognitoIdentityUserChangePasswordResponse new];
[response aws_copyPropertiesFromObject:apiResponse];
return [AWSTask taskWithResult:response];
}];
}];
}
-(AWSTask<AWSCognitoIdentityUserGetDetailsResponse *>*) getDetails {
AWSCognitoIdentityProviderGetUserRequest* request = [AWSCognitoIdentityProviderGetUserRequest new];
return [[self getSession] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserSession *> * _Nonnull task) {
request.accessToken = task.result.accessToken.tokenString;
return [[self.pool.client getUser:request] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderGetUserResponse *> * _Nonnull task) {
AWSCognitoIdentityUserGetDetailsResponse * response = [AWSCognitoIdentityUserGetDetailsResponse new];
[response aws_copyPropertiesFromObject:task.result];
return [AWSTask taskWithResult:response];
}];
}];
}
- (BOOL) isSessionValid:(AWSCognitoIdentityUserSession * _Nonnull)session {
// If id token is not present we only need to check the accessToken to determine the validity of the token.
if (!session.idToken) {
return [self isTokenValid:session.accessToken];
} else {
return [self isTokenValid:session.accessToken] && [self isTokenValid:session.idToken];
}
return false;
}
// Check if the token is valid or not. Returns true if the token is valid.
//
// The token is consider invalid if the token expiry is less than or equal to 2 min. This 2 minute buffer is
// given so that we do not hand over a token to the user which will get expired immediately. This guarrantees that the
// returned session tokens are valid for atleast 2 min.
- (BOOL) isTokenValid:(AWSCognitoIdentityUserSessionToken * _Nonnull)token {
if ([token.tokenClaims valueForKey:@"exp"]) {
int expiryWindow = 2 * 60;
NSTimeInterval expiryInterval = [[token.tokenClaims valueForKey:@"exp"] doubleValue];
NSDate *tokenExpiration = [NSDate dateWithTimeIntervalSince1970:expiryInterval];
return (tokenExpiration &&
[tokenExpiration compare:[NSDate dateWithTimeIntervalSinceNow:expiryWindow]] == NSOrderedDescending);
}
return false;
}
/**
Get a session
*/
-(AWSTask<AWSCognitoIdentityUserSession*> *) getSession {
//check to see if we have valid tokens
__block NSString * keyChainNamespace = [self keyChainNamespaceClientId];
NSString * expirationTokenKey = [self keyChainKey:keyChainNamespace key:AWSCognitoIdentityUserTokenExpiration];
NSString * expirationDate = self.pool.keychain[expirationTokenKey];
if(expirationDate){
NSDate *expiration = [NSDate aws_dateFromString:expirationDate format:AWSDateISO8601DateFormat1];
NSString * refreshToken = [self refreshTokenFromKeyChain:keyChainNamespace];
// Token exists, the user is confirmed
self.confirmedStatus = AWSCognitoIdentityUserStatusConfirmed;
NSString * accessTokenKey = [self keyChainKey:keyChainNamespace key:AWSCognitoIdentityUserAccessToken];
NSString * idTokenKey = [self keyChainKey:keyChainNamespace key:AWSCognitoIdentityUserIdToken];
NSString * idToken = self.pool.keychain[idTokenKey];
NSString * accessToken = self.pool.keychain[accessTokenKey];
AWSCognitoIdentityUserSession * session;
// Session is available if we have expiration and accessToken.
if (expiration && accessToken) {
session = [[AWSCognitoIdentityUserSession alloc] initWithIdToken:idToken
accessToken:accessToken
refreshToken:refreshToken
expirationTime:expiration];
}
// If the session expires > 2 minutes return it. We need to check both accessToken and id Token expiry
// since user can change both of them in Cognito console.
if(session
&& [self isSessionValid:session]
&& [expiration compare:[NSDate dateWithTimeIntervalSinceNow:2 * 60]] == NSOrderedDescending) {
return [AWSTask taskWithResult:session];
}
//else refresh it using the refresh token
else if(refreshToken){
AWSCognitoIdentityProviderInitiateAuthRequest * request = [AWSCognitoIdentityProviderInitiateAuthRequest new];
request.authFlow = AWSCognitoIdentityProviderAuthFlowTypeRefreshTokenAuth;
request.clientId = self.pool.userPoolConfiguration.clientId;
request.analyticsMetadata = [self.pool analyticsMetadata];
request.userContextData = [self.pool userContextData:self.username deviceId: [self asfDeviceId]];
NSMutableDictionary * authParameters = [[NSMutableDictionary alloc] initWithDictionary:@{@"REFRESH_TOKEN" : refreshToken}];
//refresh token secret hash is actually client secret for this api, set it if it is supplied
if(self.pool.userPoolConfiguration.clientSecret != nil){
[authParameters setObject:self.pool.userPoolConfiguration.clientSecret forKey:@"SECRET_HASH"];
}
[self addDeviceKey:authParameters];
request.authParameters = authParameters;
return [[self.pool.client initiateAuth:request] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderInitiateAuthResponse *> * _Nonnull task) {
if(task.error){
//If this token is no longer valid, fall back on interactive auth.
if(task.error.code == AWSCognitoIdentityProviderErrorNotAuthorized) {
return [self interactiveAuth];
} else {
return task;
}
}
AWSCognitoIdentityProviderInitiateAuthResponse *response = task.result;
AWSCognitoIdentityProviderAuthenticationResultType *authResult = response.authenticationResult;
/** Check to see if refreshToken is received in the response.
If not, load it from the keychain.
*/
NSString * refreshToken = authResult.refreshToken;
if (refreshToken == nil){
NSString * keyChainNamespace = [self keyChainNamespaceClientId];
refreshToken = [self refreshTokenFromKeyChain:keyChainNamespace];
}
AWSCognitoIdentityUserSession * session = [[AWSCognitoIdentityUserSession alloc] initWithIdToken: authResult.idToken accessToken:authResult.accessToken refreshToken:refreshToken expiresIn:authResult.expiresIn];
[self updateUsernameAndPersistTokens:session];
return [AWSTask taskWithResult:session];
}];
}
}
return [self setConfirmationStatus: [self interactiveAuth]];
}
- (AWSTask<AWSCognitoIdentityUserSession*>*) getSession:(NSString *) username
password:(NSString *) password
validationData:(NSArray<AWSCognitoIdentityUserAttributeType*>*) validationData
clientMetaData:(nullable NSDictionary<NSString *,NSString *> *) clientMetaData
isInitialCustomChallenge:(BOOL) isInitialCustomChallenge {
AWSTask *authenticationTask = nil;
if (self.pool.userPoolConfiguration.migrationEnabled) {
authenticationTask = [self migrationAuth:username
password:password
validationData:validationData
clientMetaData:clientMetaData
lastChallenge:nil];
} else {
authenticationTask = [self srpAuthInternal:username
password:password
validationData:validationData
clientMetaData:clientMetaData
lastChallenge:nil
isInitialCustomChallenge:isInitialCustomChallenge];
}
return [self setConfirmationStatus: [authenticationTask continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> * _Nonnull task) {
return [self getSessionInternal:task];
}]];
}
- (AWSTask<AWSCognitoIdentityUserSession*>*) getSession:(NSString *) username
password:(NSString *) password
validationData:(NSArray<AWSCognitoIdentityUserAttributeType*>*) validationData
isInitialCustomChallenge:(BOOL) isInitialCustomChallenge {
return [self getSession:username password:password validationData:validationData clientMetaData:nil isInitialCustomChallenge:isInitialCustomChallenge];
}
/**
* Explicitly get a session without using any cached tokens/refresh tokens.
*/
- (AWSTask<AWSCognitoIdentityUserSession*>*) getSession:(NSString *) username
password:(NSString *) password
validationData:(NSArray<AWSCognitoIdentityUserAttributeType*>*) validationData {
return [self getSession:username
password:password
validationData:validationData
clientMetaData:nil
isInitialCustomChallenge:NO];
}
- (AWSTask<AWSCognitoIdentityUserSession*>*) getSession:(NSString *) username
password:(NSString *) password
validationData:(NSArray<AWSCognitoIdentityUserAttributeType*>*) validationData
clientMetaData:(nullable NSDictionary<NSString *,NSString *> *) clientMetaData {
return [self getSession:username
password:password
validationData:validationData
clientMetaData:clientMetaData
isInitialCustomChallenge:NO];
}
- (AWSTask<AWSCognitoIdentityUserSession*>*) setConfirmationStatus: (AWSTask<AWSCognitoIdentityUserSession*>*) task {
// If the user status is unknown
if (self.confirmedStatus == AWSCognitoIdentityUserStatusUnknown) {
if (task.error) {
if (task.error.code == AWSCognitoIdentityProviderErrorUserNotConfirmed) {
self.confirmedStatus = AWSCognitoIdentityUserStatusUnconfirmed;
}
} else {
self.confirmedStatus = AWSCognitoIdentityUserStatusConfirmed;
}
}
return task;
}
- (AWSTask<AWSCognitoIdentityUserSession*>*) getSessionInternal: (AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *>*) task{
return [task continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> * _Nonnull task) {
AWSCognitoIdentityProviderRespondToAuthChallengeResponse * authenticateResult = task.result;
AWSCognitoIdentityProviderAuthenticationResultType * authResult = task.result.authenticationResult;
AWSCognitoIdentityProviderChallengeNameType nextChallenge = authenticateResult.challengeName;
AWSCognitoIdentityUserSession * session = nil;
//No more challenges we have a session
if(authResult != nil){
session = [[AWSCognitoIdentityUserSession alloc] initWithIdToken:authResult.idToken accessToken:authResult.accessToken refreshToken:authResult.refreshToken expiresIn:authResult.expiresIn];
}
//last step is to perform device auth if device key is supplied or we are being challenged with device auth
if(authResult.latestDeviceMetadata != nil || nextChallenge == AWSCognitoIdentityProviderChallengeNameTypeDeviceSrpAuth){
return [self performDeviceAuth: task session:session];
}
//if mfa required, present mfa challenge
if(AWSCognitoIdentityProviderChallengeNameTypeSmsMfa == nextChallenge || AWSCognitoIdentityProviderChallengeNameTypeSoftwareTokenMfa == nextChallenge){
if ([self.pool.delegate respondsToSelector:@selector(startMultiFactorAuthentication)]) {
BOOL isSoftwareToken = AWSCognitoIdentityProviderChallengeNameTypeSoftwareTokenMfa == nextChallenge;
id<AWSCognitoIdentityMultiFactorAuthentication> authenticationDelegate = [self.pool.delegate startMultiFactorAuthentication];
NSString *deliveryMedium = isSoftwareToken ? @"SOFTWARE_TOKEN" : authenticateResult.challengeParameters[@"CODE_DELIVERY_DELIVERY_MEDIUM"];
NSString *destination = isSoftwareToken ? authenticateResult.challengeParameters[@"FRIENDLY_DEVICE_NAME"] : authenticateResult.challengeParameters[@"CODE_DELIVERY_DESTINATION"];
return [self mfaAuthInternal:deliveryMedium destination:destination authState:authenticateResult.session challengeName:nextChallenge authenticationDelegate:authenticationDelegate];
}else {
return [AWSTask taskWithError:[NSError errorWithDomain:AWSCognitoIdentityProviderErrorDomain code:AWSCognitoIdentityProviderClientErrorInvalidAuthenticationDelegate userInfo:@{NSLocalizedDescriptionKey: @"startMultiFactorAuthentication not implemented by authentication delegate"}]];
}
}else if(AWSCognitoIdentityProviderChallengeNameTypeSelectMfaType == nextChallenge){
return [self startSelectMfaUI:authenticateResult];
}else if(AWSCognitoIdentityProviderChallengeNameTypeMfaSetup == nextChallenge){
return [self startMfaSetupRequiredUI:authenticateResult];
}else if(AWSCognitoIdentityProviderChallengeNameTypeNewPasswordRequired == nextChallenge){
return [self startNewPasswordRequiredUI:authenticateResult];
}else if(AWSCognitoIdentityProviderAuthFlowTypeUserSrpAuth == nextChallenge){ //if srp auth happens mid auth
return [self startPasswordAuthenticationUI:authenticateResult];
}else if (session) { //we have a session, return it
[self updateUsernameAndPersistTokens:session];
return [AWSTask taskWithResult:session];
}else { //this is a custom challenge
id<AWSCognitoIdentityCustomAuthentication> authenticationDelegate = nil;
// The below condition is added to support AWSMobileClient.
if (self.pool.isCustomAuth && [self.pool.delegate respondsToSelector:@selector(startCustomAuthentication_v2)]) {
authenticationDelegate = [self.pool.delegate performSelector:@selector(startCustomAuthentication_v2)];
} else if ([self.pool.delegate respondsToSelector:@selector(startCustomAuthentication)]) {
authenticationDelegate = [self.pool.delegate startCustomAuthentication];
}
if (authenticationDelegate != nil) {
if ([authenticateResult.challengeParameters objectForKey:@"USERNAME"] != nil) {
self.username = [authenticateResult.challengeParameters objectForKey:@"USERNAME"];
}
AWSCognitoIdentityCustomAuthenticationInput *input = [AWSCognitoIdentityCustomAuthenticationInput new];
input.challengeParameters = authenticateResult.challengeParameters;
AWSTaskCompletionSource<AWSCognitoIdentityCustomChallengeDetails *> *challengeDetails = [AWSTaskCompletionSource<AWSCognitoIdentityCustomChallengeDetails *> new];
[authenticationDelegate getCustomChallengeDetails:input customAuthCompletionSource:challengeDetails];
return [challengeDetails.task continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityCustomChallengeDetails *> * _Nonnull task) {
return [[self performRespondCustomAuthChallenge:task.result session:authenticateResult.session] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> * _Nonnull task) {
[authenticationDelegate didCompleteCustomAuthenticationStepWithError:task.error];
return [self getSessionInternal: task];
}];
}];
} else {
return [AWSTask taskWithError:[NSError errorWithDomain:AWSCognitoIdentityProviderErrorDomain code:AWSCognitoIdentityProviderClientErrorInvalidAuthenticationDelegate userInfo:@{NSLocalizedDescriptionKey: @"startCustomAuthentication not implemented by authentication delegate"}]];
}
}
}];
}
- (AWSTask<AWSCognitoIdentityUserSession*>*) startPasswordAuthenticationUI:(AWSCognitoIdentityProviderRespondToAuthChallengeResponse*) lastChallenge {
if([self.pool.delegate respondsToSelector:@selector(startPasswordAuthentication)]){
id<AWSCognitoIdentityPasswordAuthentication> authenticationDelegate = [self.pool.delegate startPasswordAuthentication];
return [self passwordAuthInternal:authenticationDelegate lastChallenge:lastChallenge isInitialCustomChallenge:lastChallenge == nil];
}else {
return [AWSTask taskWithError:[NSError errorWithDomain:AWSCognitoIdentityProviderErrorDomain code:AWSCognitoIdentityProviderClientErrorInvalidAuthenticationDelegate userInfo:@{NSLocalizedDescriptionKey: @"startPasswordAuthentication must be implemented on your AWSCognitoIdentityInteractiveAuthenticationDelegate"}]];
}
}
- (AWSTask<AWSCognitoIdentityUserSession*>*) startNewPasswordRequiredUI:(AWSCognitoIdentityProviderRespondToAuthChallengeResponse*) lastChallenge {
if ([self.pool.delegate respondsToSelector:@selector(startNewPasswordRequired)]) {
id<AWSCognitoIdentityNewPasswordRequired> newPasswordRequiredDelegate = [self.pool.delegate startNewPasswordRequired];
NSString * userAttributes = lastChallenge.challengeParameters[@"userAttributes"];
NSString * requiredAttributes = lastChallenge.challengeParameters[@"requiredAttributes"];
NSDictionary<NSString*, NSString *> *userAttributesDict = [NSMutableDictionary new];
NSMutableSet<NSString*> *requiredAttributesSet = [NSMutableSet new];
if(requiredAttributes) {
NSArray * requiredAttributesArray = [NSJSONSerialization JSONObjectWithData:[requiredAttributes dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
for (NSString * requiredAttribute in requiredAttributesArray) {
//strip off userAttributes. from all the attribute names
NSString *strippedKey = [requiredAttribute substringFromIndex:[AWSCognitoIdentityUserUserAttributePrefix length]];
[requiredAttributesSet addObject:strippedKey];
}
}
AWSCognitoIdentityNewPasswordRequiredInput *newPasswordRequiredInput = [[AWSCognitoIdentityNewPasswordRequiredInput alloc] initWithUserAttributes:userAttributesDict requiredAttributes:requiredAttributesSet];
AWSTaskCompletionSource<AWSCognitoIdentityNewPasswordRequiredDetails *> *newPasswordRequiredDetails = [AWSTaskCompletionSource<AWSCognitoIdentityNewPasswordRequiredDetails *> new];
[newPasswordRequiredDelegate getNewPasswordDetails:newPasswordRequiredInput newPasswordRequiredCompletionSource:newPasswordRequiredDetails];
return [[newPasswordRequiredDetails.task continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityNewPasswordRequiredDetails *> * _Nonnull task) {
return [self performRespondToNewPasswordChallenge:task.result session:lastChallenge.session];
}] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> * _Nonnull task) {
[newPasswordRequiredDelegate didCompleteNewPasswordStepWithError:task.error];
if(task.error){
return [self startNewPasswordRequiredUI:lastChallenge];
}
return [self getSessionInternal:task];
}];
}else {
return [AWSTask taskWithError:[NSError errorWithDomain:AWSCognitoIdentityProviderErrorDomain code:AWSCognitoIdentityProviderClientErrorInvalidAuthenticationDelegate userInfo:@{NSLocalizedDescriptionKey: @"startNewPasswordRequired not implemented by authentication delegate"}]];
}
}
- (AWSTask<AWSCognitoIdentityUserSession*>*) startMfaSetupRequiredUI:(AWSCognitoIdentityProviderRespondToAuthChallengeResponse*) lastChallenge {
NSString * availableMfas = lastChallenge.challengeParameters[@"MFAS_CAN_SETUP"];
NSMutableSet<NSString*> *availableMfasSet = [NSMutableSet new];
if(availableMfas) {
NSArray * availableMfasArray = [NSJSONSerialization JSONObjectWithData:[availableMfas dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
for (NSString * availableMfa in availableMfasArray) {
[availableMfasSet addObject:availableMfa];
}
}
if([availableMfasSet containsObject:@"SOFTWARE_TOKEN_MFA"]){
if ([self.pool.delegate respondsToSelector:@selector(startSoftwareMfaSetupRequired)]) {
id<AWSCognitoIdentitySoftwareMfaSetupRequired> softwareMfaSetupRequiredDelegate = [self.pool.delegate startSoftwareMfaSetupRequired];
AWSCognitoIdentityProviderAssociateSoftwareTokenRequest *request = [AWSCognitoIdentityProviderAssociateSoftwareTokenRequest new];
request.session = lastChallenge.session;
return [[self.pool.client associateSoftwareToken:request] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderAssociateSoftwareTokenResponse *> * _Nonnull task) {
AWSCognitoIdentitySoftwareMfaSetupRequiredInput *softwareMfaSetupRequiredInput = [[AWSCognitoIdentitySoftwareMfaSetupRequiredInput alloc] initWithSecretCode:task.result.secretCode username:self.username];
return [self verifyMfaSetup:task.result.session selectMfaDelegate:softwareMfaSetupRequiredDelegate input:softwareMfaSetupRequiredInput];
}];
} else {
return [AWSTask taskWithError:[NSError errorWithDomain:AWSCognitoIdentityProviderErrorDomain code:AWSCognitoIdentityProviderClientErrorInvalidAuthenticationDelegate userInfo:@{NSLocalizedDescriptionKey: @"startSoftwareMfaSetupRequired not implemented by authentication delegate"}]];
}
} else {
return [AWSTask taskWithError:[NSError errorWithDomain:AWSCognitoIdentityProviderErrorDomain code:AWSCognitoIdentityProviderClientErrorInvalidAuthenticationDelegate userInfo:@{NSLocalizedDescriptionKey: @"This version of the SDK does not support setup of the MFA types necessary to authenticate"}]];
}
}
- (AWSTask<AWSCognitoIdentityUserSession*>*) verifyMfaSetup:(NSString *) session selectMfaDelegate:(id<AWSCognitoIdentitySoftwareMfaSetupRequired> ) softwareMfaSetupRequiredDelegate input:(AWSCognitoIdentitySoftwareMfaSetupRequiredInput *) input {
AWSTaskCompletionSource<AWSCognitoIdentitySoftwareMfaSetupRequiredDetails *> *softwareMfaSetupRequiredDetails = [AWSTaskCompletionSource<AWSCognitoIdentitySoftwareMfaSetupRequiredDetails *> new];
[softwareMfaSetupRequiredDelegate getSoftwareMfaSetupDetails:input softwareMfaSetupRequiredCompletionSource:softwareMfaSetupRequiredDetails];
return [[softwareMfaSetupRequiredDetails.task continueWithSuccessBlock:^id _Nullable(AWSTask <AWSCognitoIdentitySoftwareMfaSetupRequiredDetails *>* _Nonnull mfaDetails) {
AWSCognitoIdentityProviderVerifySoftwareTokenRequest *verifyRequest = [AWSCognitoIdentityProviderVerifySoftwareTokenRequest new];
verifyRequest.session = session;
verifyRequest.friendlyDeviceName = mfaDetails.result.friendlyDeviceName;
verifyRequest.userCode = mfaDetails.result.userCode;
return [self.pool.client verifySoftwareToken:verifyRequest];
}] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderVerifySoftwareTokenResponse *> *_Nonnull verifySoftwareToken) {
[softwareMfaSetupRequiredDelegate didCompleteMfaSetupStepWithError:verifySoftwareToken.error];
if(verifySoftwareToken.error){
return [self verifyMfaSetup:session selectMfaDelegate:softwareMfaSetupRequiredDelegate input:input];
}
NSMutableDictionary<NSString *,NSString *> *challengeResponses = [NSMutableDictionary new];
return [self getSessionInternal:[self performRespondToAuthChallenge:challengeResponses challengeName:AWSCognitoIdentityProviderChallengeNameTypeMfaSetup session:verifySoftwareToken.result.session]];
}];
}
- (AWSTask<AWSCognitoIdentityUserSession*>*) startSelectMfaUI:(AWSCognitoIdentityProviderRespondToAuthChallengeResponse*) lastChallenge {
if ([self.pool.delegate respondsToSelector:@selector(startSelectMfa)]) {
id<AWSCognitoIdentitySelectMfa> selectMfaDelegate = [self.pool.delegate startSelectMfa];
NSString * availableMfas = lastChallenge.challengeParameters[@"MFAS_CAN_CHOOSE"];
NSMutableDictionary<NSString*,NSString*> *availableMfasDict = [NSMutableDictionary new];
if(availableMfas) {
NSArray * availableMfasArray = [NSJSONSerialization JSONObjectWithData:[availableMfas dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
for (NSString * availableMfa in availableMfasArray) {
NSString *value = nil;
if([@"SOFTWARE_TOKEN_MFA" isEqualToString:availableMfa]){
value = lastChallenge.challengeParameters[@"FRIENDLY_DEVICE_NAME"];
}else if([@"SMS_MFA" isEqualToString:availableMfa]){
value = lastChallenge.challengeParameters[@"CODE_DELIVERY_DESTINATION"];
}
if(value == nil){
value = @"unknown";
}
[availableMfasDict setObject:value forKey:availableMfa];
}
}
AWSCognitoIdentitySelectMfaInput *selectMfaInput = [[AWSCognitoIdentitySelectMfaInput alloc] initWithAvailableMfas:availableMfasDict];
AWSTaskCompletionSource<AWSCognitoIdentitySelectMfaDetails *> *selectMfaDetails = [AWSTaskCompletionSource<AWSCognitoIdentitySelectMfaDetails *> new];
[selectMfaDelegate getSelectMfaDetails:selectMfaInput selectMfaCompletionSource:selectMfaDetails];
return [[selectMfaDetails.task continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentitySelectMfaDetails *> * _Nonnull task) {
return [self performRespondToSelectMfaChallenge:task.result session:lastChallenge.session];
}] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> * _Nonnull task) {
[selectMfaDelegate didCompleteSelectMfaStepWithError:task.error];
if(task.error){
return [self startSelectMfaUI:lastChallenge];
}
return [self getSessionInternal:task];
}];
}else {
return [AWSTask taskWithError:[NSError errorWithDomain:AWSCognitoIdentityProviderErrorDomain code:AWSCognitoIdentityProviderClientErrorInvalidAuthenticationDelegate userInfo:@{NSLocalizedDescriptionKey: @"startSelectMfa not implemented by authentication delegate"}]];
}
}
- (AWSTask<AWSCognitoIdentityUserSession*>*) performDeviceAuth:(AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *>*) lastChallengeResponse session: (AWSCognitoIdentityUserSession *) session {
if(session){
[self updateUsernameAndPersistTokens:session];
}
if(lastChallengeResponse.result.challengeName == AWSCognitoIdentityProviderChallengeNameTypeDeviceSrpAuth){
return [[self deviceAuthInternal:lastChallengeResponse] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> * _Nonnull task) {
if(task.cancelled || task.error) {
return task;
}else {
AWSCognitoIdentityProviderRespondToAuthChallengeResponse *response = task.result;
AWSCognitoIdentityUserSession * session = [[AWSCognitoIdentityUserSession alloc] initWithIdToken:response.authenticationResult.idToken accessToken:response.authenticationResult.accessToken refreshToken:response.authenticationResult.refreshToken expiresIn:response.authenticationResult.expiresIn];
[self updateUsernameAndPersistTokens:session];
return [AWSTask taskWithResult:session];
}
}];
}else {
return [[self confirmDeviceInternal:lastChallengeResponse.result.authenticationResult] continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) {
if(task.error || task.isCancelled){
return task;
}else {
return [AWSTask taskWithResult:session];
}
}];
}
}
/**
* Generates a device password, calls service to exchange the password verifier and prompts user to remember the device as required.
*/
- (AWSTask*) confirmDeviceInternal:(AWSCognitoIdentityProviderAuthenticationResultType *) authResult {
if(authResult.latestDeviceMetadata != nil){
NSString * deviceKey = authResult.latestDeviceMetadata.deviceKey;
NSString * deviceGroup = authResult.latestDeviceMetadata.deviceGroupKey;
if(deviceKey != nil){
NSString *secret = [[NSUUID UUID] UUIDString];
AWSCognitoIdentityProviderConfirmDeviceRequest * request = [AWSCognitoIdentityProviderConfirmDeviceRequest new];
request.accessToken = authResult.accessToken;
request.deviceKey = deviceKey;
request.deviceName = [[UIDevice currentDevice] name];
AWSCognitoIdentityProviderSrpHelper * srpHelper = [[AWSCognitoIdentityProviderSrpHelper alloc] initWithPoolName:deviceGroup userName:deviceKey password:secret];
request.deviceSecretVerifierConfig = [AWSCognitoIdentityProviderDeviceSecretVerifierConfigType new];
request.deviceSecretVerifierConfig.salt = [[NSData aws_dataWithSignedBigInteger:srpHelper.salt] base64EncodedStringWithOptions:0];
request.deviceSecretVerifierConfig.passwordVerifier = [[NSData aws_dataWithSignedBigInteger:srpHelper.v] base64EncodedStringWithOptions:0];
return [[self.pool.client confirmDevice:request] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderConfirmDeviceResponse *> * _Nonnull task) {
[self persistDevice:deviceKey deviceSecret:secret deviceGroup:deviceGroup];
AWSCognitoIdentityProviderConfirmDeviceResponse *confirmDeviceResponse = task.result;
if([confirmDeviceResponse.userConfirmationNecessary boolValue]) {
if ([self.pool.delegate respondsToSelector:@selector(startRememberDevice)]) {
id<AWSCognitoIdentityRememberDevice> rememberDeviceStep = [self.pool.delegate startRememberDevice];
AWSTaskCompletionSource<NSNumber *> *rememberDevice = [[AWSTaskCompletionSource<NSNumber *> alloc] init];
[rememberDeviceStep getRememberDevice:rememberDevice];
return [rememberDevice.task continueWithBlock:^id _Nullable(AWSTask<NSNumber *> * _Nonnull rememberDeviceTask) {
if(rememberDeviceTask.isCancelled || rememberDeviceTask.error){
[rememberDeviceStep didCompleteRememberDeviceStepWithError:rememberDeviceTask.error];
return rememberDeviceStep;
}else if ([rememberDeviceTask.result boolValue]){
AWSCognitoIdentityProviderUpdateDeviceStatusRequest * request = [AWSCognitoIdentityProviderUpdateDeviceStatusRequest new];
request.accessToken = authResult.accessToken;
request.deviceKey = deviceKey;
request.deviceRememberedStatus = AWSCognitoIdentityProviderDeviceRememberedStatusTypeRemembered;
return [[self.pool.client updateDeviceStatus:request] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderUpdateDeviceStatusResponse *> * _Nonnull updateDeviceStatusTask) {
[rememberDeviceStep didCompleteRememberDeviceStepWithError:rememberDeviceTask.error];
return updateDeviceStatusTask;
}];
}
return task;
}];
}else {
AWSDDLogWarn(@"startRememberDevice is not implemented by authentication delegate, defaulting to not remembered.");
}
}
return task;
}];
}
}
return [AWSTask taskWithResult:nil];
}
/**
* Kick off interactive auth to prompt developer to challenge end user for credentials
*/
- (AWSTask<AWSCognitoIdentityUserSession*>*) interactiveAuth {
if (self.pool.delegate != nil) {
// The below condition is added to support AWSMobileClient.
if (self.pool.isCustomAuth &&
[self.pool.delegate respondsToSelector:@selector(startCustomAuthentication_v2)]) {
id<AWSCognitoIdentityCustomAuthentication> authenticationDelegate = [self.pool.delegate performSelector:@selector(startCustomAuthentication_v2)];
return [self customAuthInternal:authenticationDelegate];
}
if ([self.pool.delegate respondsToSelector:@selector(startCustomAuthentication)] && !self.pool.userPoolConfiguration.migrationEnabled) {
id<AWSCognitoIdentityCustomAuthentication> authenticationDelegate = [self.pool.delegate startCustomAuthentication];
return [self customAuthInternal:authenticationDelegate];
}
if ([self.pool.delegate respondsToSelector:@selector(startPasswordAuthentication)]) {
id<AWSCognitoIdentityPasswordAuthentication> authenticationDelegate = [self.pool.delegate startPasswordAuthentication];
return [self passwordAuthInternal:authenticationDelegate lastChallenge:nil isInitialCustomChallenge:NO];
}
return [AWSTask taskWithError:[NSError errorWithDomain:AWSCognitoIdentityProviderErrorDomain
code:AWSCognitoIdentityProviderClientErrorInvalidAuthenticationDelegate userInfo:@{NSLocalizedDescriptionKey: @"Either startCustomAuthentication or startPasswordAuthentication must be implemented on your AWSCognitoIdentityInteractiveAuthenticationDelegate"}]];
} else {
return [AWSTask taskWithError:[NSError errorWithDomain:AWSCognitoIdentityProviderErrorDomain
code:AWSCognitoIdentityProviderClientErrorInvalidAuthenticationDelegate userInfo:@{NSLocalizedDescriptionKey: @"Authentication delegate not set"}]];
};
}
/**
* Prompt developer to obtain username/password and do SRP auth
*/
- (AWSTask<AWSCognitoIdentityUserSession*>*) passwordAuthInternal: (id<AWSCognitoIdentityPasswordAuthentication>) authenticationDelegate
lastChallenge:(AWSCognitoIdentityProviderRespondToAuthChallengeResponse*) lastChallenge
isInitialCustomChallenge:(BOOL) isInitialCustomChallenge {
AWSCognitoIdentityPasswordAuthenticationInput * input = [[AWSCognitoIdentityPasswordAuthenticationInput alloc] initWithLastKnownUsername:[self.pool currentUsername]];
AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails*>*passwordAuthenticationDetails = [AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails*> new];
[authenticationDelegate getPasswordAuthenticationDetails:input
passwordAuthenticationCompletionSource:passwordAuthenticationDetails];
return [passwordAuthenticationDetails.task continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityPasswordAuthenticationDetails *> * _Nonnull task) {
AWSCognitoIdentityPasswordAuthenticationDetails * authDetails = task.result;
if (self.pool.userPoolConfiguration.migrationEnabled) {
return [[self migrationAuth:authDetails.username
password:authDetails.password
validationData:authDetails.validationData
clientMetaData:nil
lastChallenge:lastChallenge]
continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> * _Nonnull task) {
[authenticationDelegate didCompletePasswordAuthenticationStepWithError:task.error];
if (task.isCancelled) {
return task;
}
if (task.error) {
//retry password auth on error
return [self passwordAuthInternal:authenticationDelegate
lastChallenge:lastChallenge
isInitialCustomChallenge:NO];
} else {
//morph this initiate auth response into a respond to auth challenge response so it works as input to getSessionInternal
AWSCognitoIdentityProviderRespondToAuthChallengeResponse * response = [AWSCognitoIdentityProviderRespondToAuthChallengeResponse new];
[response aws_copyPropertiesFromObject:task.result];
return [self getSessionInternal:[AWSTask taskWithResult:response]];
}
}];
} else {
return [[self srpAuthInternal:authDetails.username
password:authDetails.password
validationData:authDetails.validationData
clientMetaData:nil
lastChallenge:lastChallenge
isInitialCustomChallenge:isInitialCustomChallenge]
continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> * _Nonnull task) {
[authenticationDelegate didCompletePasswordAuthenticationStepWithError:task.error];
if (task.isCancelled) {
return task;
}
if (task.error) {
//retry password auth on error
return [self passwordAuthInternal:authenticationDelegate
lastChallenge:lastChallenge
isInitialCustomChallenge:isInitialCustomChallenge];
} else {
return [self getSessionInternal:task];
}
}];
}
}];
}
/**
* Pass username and password in plaintext so developer can validate login and migrate as appropriate.
**/
- (AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse*>*) migrationAuth:(NSString *)username
password:(NSString *)password
validationData:(NSArray<AWSCognitoIdentityUserAttributeType*>*)validationData
clientMetaData:(nullable NSDictionary<NSString *,NSString *> *)clientMetaData
lastChallenge:(AWSCognitoIdentityProviderRespondToAuthChallengeResponse*) lastChallenge {
self.username = username;
NSMutableDictionary *challengeResponses = [NSMutableDictionary new];
[self addSecretHashDeviceKeyAndUsername:challengeResponses];
[challengeResponses setObject:password forKey:@"PASSWORD"];
if(lastChallenge){
AWSCognitoIdentityProviderRespondToAuthChallengeRequest *input = [AWSCognitoIdentityProviderRespondToAuthChallengeRequest new];
input.challengeName = lastChallenge.challengeName;
input.challengeResponses = challengeResponses;
input.session = lastChallenge.session;
input.analyticsMetadata = [self.pool analyticsMetadata];
input.userContextData = [self.pool userContextData:self.username deviceId: [self asfDeviceId]];
input.clientMetadata = clientMetaData;
return [[self.pool.client respondToAuthChallenge:input] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> * _Nonnull task) {
return [self forgetDeviceOnRespondDeviceNotFoundError:task retryContinuation:^AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> *{
return [self migrationAuth:username password:password validationData:validationData clientMetaData:clientMetaData lastChallenge:lastChallenge];
}];
}];
}
else{
AWSCognitoIdentityProviderInitiateAuthRequest *input = [AWSCognitoIdentityProviderInitiateAuthRequest new];
input.clientId = self.pool.userPoolConfiguration.clientId;
input.clientMetadata = [self.pool getValidationData:validationData clientMetaData: clientMetaData];
input.analyticsMetadata = [self.pool analyticsMetadata];
input.userContextData = [self.pool userContextData:self.username deviceId: [self asfDeviceId]];
input.authFlow = AWSCognitoIdentityProviderAuthFlowTypeUserPasswordAuth;
input.authParameters = challengeResponses;
return [[self.pool.client initiateAuth:input] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderInitiateAuthResponse *> * _Nonnull task) {
//if there was an error, it may be due to the device being forgotten, reset the device and retry if that is the case
return [self forgetDeviceOnInitiateDeviceNotFoundError:task retryContinuation:^AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> *{
return [self migrationAuth:username password:password validationData:validationData clientMetaData:clientMetaData lastChallenge:lastChallenge];
}];
}];
}
}
/**
* Prompt developer to obtain custom challenge details
*/
- (AWSTask<AWSCognitoIdentityUserSession*>*) customAuthInternal: (id<AWSCognitoIdentityCustomAuthentication>) authenticationDelegate {
AWSTaskCompletionSource<AWSCognitoIdentityCustomChallengeDetails *> *customAuthenticationDetails = [AWSTaskCompletionSource<AWSCognitoIdentityCustomChallengeDetails *> new];
AWSCognitoIdentityCustomAuthenticationInput *input = [[AWSCognitoIdentityCustomAuthenticationInput alloc] initWithChallengeParameters: [NSDictionary new]];
[authenticationDelegate getCustomChallengeDetails:input customAuthCompletionSource:customAuthenticationDetails];
return [customAuthenticationDetails.task continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityCustomChallengeDetails *> * _Nonnull task) {
//if first challenge is SRP auth
if([self isFirstCustomStepSRP:task.result]){
return [self startPasswordAuthenticationUI:nil];
}else {
return [[self performInitiateCustomAuthChallenge:task.result]
continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderInitiateAuthResponse *> * _Nonnull task) {
[authenticationDelegate didCompleteCustomAuthenticationStepWithError:task.error];
if(task.isCancelled){
return task;
}
if(task.error){
//retry auth on error
return [self customAuthInternal:authenticationDelegate];
}else {
//morph this initiate auth response into a respond to auth challenge response so it works as input to getSessionInternal
AWSCognitoIdentityProviderRespondToAuthChallengeResponse * response = [AWSCognitoIdentityProviderRespondToAuthChallengeResponse new];
[response aws_copyPropertiesFromObject:task.result];
return [self getSessionInternal:[AWSTask taskWithResult:response]];
}
}];
}
}];
}
- (BOOL) isFirstCustomStepSRP: (AWSCognitoIdentityCustomChallengeDetails *) customAuthenticationDetails {
return customAuthenticationDetails.initialChallengeName != nil && [@"SRP_A" isEqualToString: customAuthenticationDetails.initialChallengeName];
}
/**
* Run initiate auth on challenge responses from end user for custom auth
*/
- (AWSTask<AWSCognitoIdentityProviderInitiateAuthResponse*>*) performInitiateCustomAuthChallenge: (AWSCognitoIdentityCustomChallengeDetails *) challengeDetails {
AWSCognitoIdentityProviderInitiateAuthRequest *input = [AWSCognitoIdentityProviderInitiateAuthRequest new];
input.clientId = self.pool.userPoolConfiguration.clientId;
input.clientMetadata = [self.pool getValidationData:challengeDetails.validationData clientMetaData:challengeDetails.clientMetaData];
input.analyticsMetadata = [self.pool analyticsMetadata];
input.userContextData = [self.pool userContextData:self.username deviceId: [self asfDeviceId]];
NSMutableDictionary * authParameters = [[NSMutableDictionary alloc] initWithDictionary:challengeDetails.challengeResponses];
[self addSecretHashDeviceKeyAndUsername:authParameters];
if(challengeDetails.initialChallengeName != nil){
[authParameters setObject:challengeDetails.initialChallengeName forKey:@"CHALLENGE_NAME"];
}
input.authFlow = AWSCognitoIdentityProviderAuthFlowTypeCustomAuth;
input.authParameters = authParameters;
return [[self.pool.client initiateAuth:input] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderInitiateAuthResponse *> * _Nonnull task) {
//if there was an error, it may be due to the device being forgotten, reset the device and retry if that is the case
return [self forgetDeviceOnInitiateDeviceNotFoundError:task retryContinuation:^AWSTask *{
return [self performInitiateCustomAuthChallenge:challengeDetails];
}];
}];
}
/**
* Run respond to auth challenges on challenge responses from end user for custom auth
*/
- (AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse*>*) performRespondCustomAuthChallenge: (AWSCognitoIdentityCustomChallengeDetails *) challengeDetails session: (NSString *) session{
NSMutableDictionary<NSString *,NSString *> *challengeResponses = [NSMutableDictionary new];
[challengeResponses addEntriesFromDictionary:challengeDetails.challengeResponses];
if([challengeResponses objectForKey:@"USERNAME"] != nil){
self.username = [challengeResponses objectForKey:@"USERNAME"];
}
return [[self performRespondToAuthChallenge: challengeResponses
challengeName: AWSCognitoIdentityProviderChallengeNameTypeCustomChallenge
clientMetaData: challengeDetails.clientMetaData
session: session] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> * _Nonnull task) {
//if there was an error, it may be due to the device being forgotten, reset the device and retry if that is the case
return [self forgetDeviceOnRespondDeviceNotFoundError:task retryContinuation:^AWSTask *{
return [self performRespondCustomAuthChallenge:challengeDetails session:session];
}];
}];
}
/**
* Run respond to auth challenges on new password required responses from end user
*/
- (AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse*>*) performRespondToNewPasswordChallenge: (AWSCognitoIdentityNewPasswordRequiredDetails *) details session: (NSString *) session{
NSMutableDictionary<NSString *,NSString *> *challengeResponses = [NSMutableDictionary new];
[challengeResponses setObject:details.proposedPassword forKey:@"NEW_PASSWORD"];
for(AWSCognitoIdentityUserAttributeType *userAttribute in details.userAttributes){
[challengeResponses setObject:userAttribute.value forKey: [NSString stringWithFormat:@"%@%@", AWSCognitoIdentityUserUserAttributePrefix, userAttribute.name]];
}
return [self performRespondToAuthChallenge:challengeResponses
challengeName:AWSCognitoIdentityProviderChallengeNameTypeNewPasswordRequired
clientMetaData: details.clientMetaData
session:session];
}
/**
* Run respond to auth challenges on select mfa responses from end user
*/
- (AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse*>*) performRespondToSelectMfaChallenge: (AWSCognitoIdentitySelectMfaDetails *) details session: (NSString *) session{
NSMutableDictionary<NSString *,NSString *> *challengeResponses = [NSMutableDictionary new];
[challengeResponses setObject:details.selectedMfa forKey:@"ANSWER"];
return [self performRespondToAuthChallenge:challengeResponses challengeName:AWSCognitoIdentityProviderChallengeNameTypeSelectMfaType session:session];
}
/**
* Run respond to auth challenges
*/
- (AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse*>*) performRespondToAuthChallenge: (NSMutableDictionary *) challengeResponses
challengeName: (AWSCognitoIdentityProviderChallengeNameType) challengeName
session: (NSString *) session {
return [self performRespondToAuthChallenge:challengeResponses
challengeName:challengeName
clientMetaData: nil
session:session];
}
/**
* Run respond to auth challenges
*/
- (AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse*>*) performRespondToAuthChallenge:(NSMutableDictionary *) challengeResponses
challengeName:(AWSCognitoIdentityProviderChallengeNameType) challengeName
clientMetaData:(NSDictionary *) clientMetaData
session:(NSString *) session {
AWSCognitoIdentityProviderRespondToAuthChallengeRequest *request = [AWSCognitoIdentityProviderRespondToAuthChallengeRequest new];
request.session = session;
request.clientId = self.pool.userPoolConfiguration.clientId;
request.challengeName = challengeName;
request.clientMetadata = clientMetaData;
request.analyticsMetadata = [self.pool analyticsMetadata];
request.userContextData = [self.pool userContextData:self.username deviceId: [self asfDeviceId]];
[self addSecretHashDeviceKeyAndUsername:challengeResponses];
request.challengeResponses = challengeResponses;
return [self.pool.client respondToAuthChallenge:request];
}
/**
* Perform SRP based authentication (initiateAuth(SRP_AUTH) and respondToAuthChallenge) given a username and password. If lastChallenge is supplied it starts with respondToAuthChallenge instead of initiate.
*/
- (AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse*>*) srpAuthInternal:(NSString *)username
password:(NSString *)password
validationData:(NSArray<AWSCognitoIdentityUserAttributeType*>*)validationData
clientMetaData:(nullable NSDictionary<NSString *,NSString *> *) clientMetaData
lastChallenge:(AWSCognitoIdentityProviderRespondToAuthChallengeResponse*) lastChallenge isInitialCustomChallenge:(BOOL) isInitialCustomChallenge {
self.username = username;
AWSCognitoIdentityProviderSrpHelper *srpHelper = [AWSCognitoIdentityProviderSrpHelper beginUserAuthentication:self.username password:password];
NSMutableDictionary * challengeResponses = [[NSMutableDictionary alloc] initWithDictionary:@{@"SRP_A" : [srpHelper.clientState.publicA stringValueWithRadix:16]}];
[self addSecretHashDeviceKeyAndUsername:challengeResponses];
if(lastChallenge){
AWSCognitoIdentityProviderRespondToAuthChallengeRequest *input = [AWSCognitoIdentityProviderRespondToAuthChallengeRequest new];
input.clientId = self.pool.userPoolConfiguration.clientId;
input.challengeName = lastChallenge.challengeName;
input.challengeResponses = challengeResponses;
input.session = lastChallenge.session;
input.analyticsMetadata = [self.pool analyticsMetadata];
input.userContextData = [self.pool userContextData:self.username deviceId: [self asfDeviceId]];
input.clientMetadata = clientMetaData;
return [[self.pool.client respondToAuthChallenge:input] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> * _Nonnull task) {
//if there was an error, it may be due to the device being forgotten, reset the device and retry if that is the case
return [[self forgetDeviceOnRespondDeviceNotFoundError:task retryContinuation:^AWSTask<AWSCognitoIdentityProviderRespondToAuthChallengeResponse *> *{
return [self srpAuthInternal:username password:password validationData:validationData clientMetaData: clientMetaData lastChallenge:lastChallenge isInitialCustomChallenge:isInitialCustomChallenge];
}] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityProviderInitiateAuthResponse *> * _Nonnull task) {
//morph this initiate auth response into a respond to auth challenge response so it works as input to srpAuthInternalStep2
AWSCognitoIdentityProviderRespondToAuthChallengeResponse * response = [AWSCognitoIdentityProviderRespondToAuthChallengeResponse new];
[response aws_copyPropertiesFromObject:task.result];
//continue with second step of SRP auth
return [self srpAuthInternalStep2:[AWSTask taskWithResult:response] srpHelper:srpHelper clientMetaData:clientMetaData];
}];
}];
}else{
AWSCognitoIdentityProviderInitiateAuthRequest *input = [AWSCognitoIdentityProviderInitiateAuthRequest new];
input.clientId = self.pool.userPoolConfiguration.clientId;
input.clientMetadata = [self.pool getValidationData:validationData clientMetaData:clientMetaData];
input.analyticsMetadata = [self.pool analyticsMetadata];
input.userContextData = [self.pool userContextData:self.username deviceId: [self asfDeviceId]];
//based on whether this is custom auth or not set the auth flow
if(isInitialCustomChallenge){
input.authFlow = AWSCognitoIdentityProviderAuthFlowTypeCustomAuth;
//set challenge name parameter to SRP_A