forked from aws-amplify/aws-sdk-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAWSCognitoAuth.m
1465 lines (1295 loc) · 67.3 KB
/
AWSCognitoAuth.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 2010-2017 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.
//
#import "AWSCognitoAuth_Internal.h"
#import <AWSCognitoIdentityProviderASF/AWSCognitoIdentityProviderASF.h>
#import <SafariServices/SafariServices.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
#import <AWSCore/AWSCore.h>
NSString *const AWSCognitoAuthErrorDomain = @"com.amazon.cognito.AWSCognitoAuthErrorDomain";
@interface AWSCognitoAuth()<SFSafariViewControllerDelegate, NSURLConnectionDelegate, UIAdaptivePresentationControllerDelegate>
@property (atomic, readwrite) AWSCognitoAuthGetSessionBlock getSessionBlock;
@property (atomic, readwrite) AWSCognitoAuthSignOutBlock signOutBlock;
@property (atomic, readwrite) NSError * getSessionError;
@property (atomic, readwrite) NSError * signOutError;
@property (atomic, readwrite) SFSafariViewController *svc;
@property (atomic, readwrite) UIViewController * pvc;
@property (atomic, readwrite) NSString * state;
@property (atomic, readwrite) NSString * proofKey;
@property (atomic, readwrite) NSString * proofKeyHash;
@property (atomic, readwrite) NSMutableData * responseData;
@property (nonatomic, strong) NSOperationQueue * getSessionQueue;
@property (nonatomic, strong) NSOperationQueue * signOutQueue;
@property (nonatomic) BOOL useSFAuthenticationSession;
@property (nonatomic) BOOL sfAuthenticationSessionAvailable;
@property (nonatomic) BOOL isHandlingRedirection;
@property (nonatomic) BOOL isAuthProviderExternal;
@property (nonatomic) BOOL isProcessingSignOut;
@property (nonatomic) BOOL isProcessingSignIn;
@end
API_AVAILABLE(ios(11.0))
@interface AWSCognitoAuth()
// SFAuthenticationSession was deprecated in iOS 12, but keeping it for flows without a presentationAnchor
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
@property (nonatomic, strong) SFAuthenticationSession *sfAuthSession;
#pragma clang diagnostic pop
@end
API_AVAILABLE(ios(13.0))
@interface AWSCognitoAuth()<ASWebAuthenticationPresentationContextProviding>
@property (nonatomic, strong) ASWebAuthenticationSession *asAuthSession;
@property (nonatomic, weak) ASPresentationAnchor presentationAnchor;
@end
@interface AWSCognitoAuthConfiguration()
@property (nonatomic, readwrite) NSString * signInUri;
@property (nonatomic, readwrite) NSString * tokensUri;
@property (nonatomic, readwrite) NSString * signOutUri;
@property (nonatomic, readwrite) NSDictionary<NSString *, NSString *> * signInUriQueryParameters;
@property (nonatomic, readwrite) NSDictionary<NSString *, NSString *> * tokensUriQueryParameters;
@property (nonatomic, readwrite) NSDictionary<NSString *, NSString *> * signOutUriQueryParameters;
@property (nonatomic) BOOL isAuthProviderExternal;
@property (nonatomic) BOOL isSignInPrivateSession;
@property (nonatomic) AWSServiceConfiguration * userPoolConfig;
@end
@implementation AWSCognitoAuth
NSString *const AWSCognitoAuthSDKVersion = @"2.36.3";
static NSMutableDictionary *_instanceDictionary = nil;
static dispatch_queue_t _dispatchQueue = nil;
static NSString *const AWSInfoCognitoAuth = @"CognitoUserPool"; //Consistent with AWSCognitoIdentityUserPool name
NSString *const AWSCognitoAuthUserAccessToken = @"accessToken"; //Consistent with AWSCognitoIdentityUserPool name
static const NSString * AWSCognitoAuthUserIdToken = @"idToken"; //Consistent with AWSCognitoIdentityUserPool name
static const NSString * AWSCognitoAuthUserRefreshToken = @"refreshToken"; //Consistent with AWSCognitoIdentityUserPool name
static const NSString * AWSCognitoAuthUserScopes = @"scopes";
static const NSString * AWSCognitoAuthUserTokenExpiration = @"tokenExpiration"; //Consistent with AWSCognitoIdentityUserPool name
static NSString * AWSCognitoAuthUserPoolCurrentUser = @"currentUser"; //Consistent with AWSCognitoIdentityUserPool name
static NSString *const AWSCognitoAuthAppClientIdLegacy = @"CognitoUserPoolAppClientId"; //Consistent with AWSCognitoIdentityUserPool name
static NSString *const AWSCognitoAuthAppClientSecretLegacy = @"CognitoUserPoolAppClientSecret"; //Consistent with AWSCognitoIdentityUserPool name
static NSString *const AWSCognitoAuthAppClientId = @"AppClientId"; //Consistent with AWSCognitoIdentityUserPool name
static NSString *const AWSCognitoAuthAppClientSecret = @"AppClientSecret"; //Consistent with AWSCognitoIdentityUserPool name
static NSString *const AWSCognitoAuthWebDomainLegacy = @"CognitoAuthWebDomain";
static NSString *const AWSCognitoAuthScopesLegacy = @"CognitoAuthScopes";
static NSString *const AWSCognitoAuthSignInRedirectUriLegacy = @"CognitoAuthSignInRedirectUri";
static NSString *const AWSCognitoAuthSignOutRedirectUriLegacy = @"CognitoAuthSignOutRedirectUri";
static NSString *const AWSCognitoAuthWebDomain = @"WebDomain";
static NSString *const AWSCognitoAuthScopes = @"Scopes";
static NSString *const AWSCognitoAuthSignInRedirectUri = @"SignInRedirectUri";
static NSString *const AWSCognitoAuthSignOutRedirectUri = @"SignOutRedirectUri";
static NSString *const AWSCognitoAuthIdpIdentifier = @"IdpIdentifier";
static NSString *const AWSCognitoAuthIdentityProvider = @"IdentityProvider";
static NSString *const AWSCognitoAuthPoolId = @"PoolIdForEnablingASF";
static NSString *const AWSCognitoAuthUseSFAuthSession = @"EnableSFAuthenticationSesssion";
static NSString *const AWSCognitoAuthUnknown = @"Unknown";
static NSString * AWSCognitoAuthAsfDeviceId = @"asf.device.id";
#pragma mark init and configuration
+ (instancetype)defaultCognitoAuth {
static AWSCognitoAuth *_defaultAuth = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//get config from Info.plist
NSDictionary * infoDictionary = [[NSBundle mainBundle] infoDictionary][@"AWS"][AWSInfoCognitoAuth][@"Default"];
NSString *appClientId = infoDictionary[AWSCognitoAuthAppClientId] ?: infoDictionary[AWSCognitoAuthAppClientIdLegacy];
NSString *appClientSecret = infoDictionary[AWSCognitoAuthAppClientSecret] ?: infoDictionary[AWSCognitoAuthAppClientSecretLegacy];
NSString *webDomain = infoDictionary[AWSCognitoAuthWebDomain] ?: infoDictionary[AWSCognitoAuthWebDomainLegacy];
NSSet<NSString *> *scopesSet;
scopesSet = infoDictionary[AWSCognitoAuthScopes]!=nil?[NSSet setWithArray:infoDictionary[AWSCognitoAuthScopes]]:nil;
if (!scopesSet) {
scopesSet = infoDictionary[AWSCognitoAuthScopesLegacy]!=nil?[NSSet setWithArray:infoDictionary[AWSCognitoAuthScopesLegacy]]:nil;
}
NSSet<NSString *> *scopes = scopesSet;
NSString *signInRedirectUri = infoDictionary[AWSCognitoAuthSignInRedirectUri] ?: infoDictionary[AWSCognitoAuthSignInRedirectUriLegacy];
NSString *signOutRedirectUri = infoDictionary[AWSCognitoAuthSignOutRedirectUri] ?: infoDictionary[AWSCognitoAuthSignOutRedirectUriLegacy];
NSString *idpIdentifier = infoDictionary[AWSCognitoAuthIdpIdentifier];
NSString *identityProvider = infoDictionary[AWSCognitoAuthIdentityProvider];
NSString *userPoolId = infoDictionary[AWSCognitoAuthPoolId];
BOOL useSFAuthSession = infoDictionary[AWSCognitoAuthUseSFAuthSession];
if (appClientId && webDomain && scopes && signOutRedirectUri && signInRedirectUri) {
AWSCognitoAuthConfiguration *authConfiguration = [[AWSCognitoAuthConfiguration alloc] initWithAppClientId:appClientId
appClientSecret:appClientSecret
scopes:scopes
signInRedirectUri:signInRedirectUri
signOutRedirectUri:signOutRedirectUri
webDomain:webDomain
identityProvider:identityProvider
idpIdentifier:idpIdentifier
userPoolIdForEnablingASF:userPoolId
enableSFAuthSessionIfAvailable:useSFAuthSession];
_defaultAuth = [[AWSCognitoAuth alloc] initWithConfiguration:authConfiguration];
} else {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"The service configuration is `nil`. You need to configure `Info.plist` before using this method."
userInfo:nil];
}
});
return _defaultAuth;
}
+ (void)registerCognitoAuthWithAuthConfiguration:(AWSCognitoAuthConfiguration *) authConfiguration
forKey:(NSString *)key {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instanceDictionary = [NSMutableDictionary new];
_dispatchQueue = dispatch_queue_create("com.amazonaws.AWSCognitoAuthDictionary", DISPATCH_QUEUE_SERIAL);
});
AWSCognitoAuth *cognitoAuth = [[AWSCognitoAuth alloc] initWithConfiguration:authConfiguration];
[self setObject:cognitoAuth
forKey:key];
}
+ (instancetype)CognitoAuthForKey:(NSString *)key {
return [self objectForKey:key];
}
+ (void)removeCognitoAuthForKey:(NSString *)key {
[self removeObjectForKey:key];
}
- (instancetype)init {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"`- init` is not a valid initializer. Use `+ defaultCognitoAuth` or `+ CognitoAuthForKey:` instead."
userInfo:nil];
return nil;
}
// Internal init method
- (instancetype)initWithConfiguration:(AWSCognitoAuthConfiguration *)authConfiguration; {
if (self = [super init]) {
_signOutQueue = [NSOperationQueue new];
_signOutQueue.maxConcurrentOperationCount = 1;
_getSessionQueue = [NSOperationQueue new];
_getSessionQueue.maxConcurrentOperationCount = 1;
_authConfiguration = [authConfiguration copy];
_useSFAuthenticationSession = authConfiguration.isSFAuthenticationSessionEnabled;
_sfAuthenticationSessionAvailable = NO;
_keychain = [AWSCognitoAuthUICKeyChainStore keyChainStoreWithService:[NSString stringWithFormat:@"%@.%@", [NSBundle mainBundle].bundleIdentifier, @"AWSCognitoIdentityUserPool"]]; //Consistent with AWSCognitoIdentityUserPool
[_keychain migrateToCurrentAccessibility];
}
return self;
}
- (NSString *) refreshTokenFromKeyChain: (NSString *) keyChainNamespace {
NSString * refreshTokenKey = [self keyChainKey:keyChainNamespace key:AWSCognitoAuthUserRefreshToken];
NSString * refreshToken = self.keychain[refreshTokenKey];
return refreshToken;
}
- (BOOL) isSignedIn {
NSString * keyChainNamespace = [self keyChainNamespaceClientId: [self currentUsername]];
NSString * refreshToken = [self refreshTokenFromKeyChain:keyChainNamespace];
return refreshToken!=nil;
}
- (void)launchSignInWithViewController:(UIViewController *) vc
completion:(nullable AWSCognitoAuthGetSessionBlock) completion {
[self launchUsing:nil uiViewController:vc completion:completion];
}
- (void)launchSignInWithWebUI:(nonnull ASPresentationAnchor) anchor
completion:(nullable AWSCognitoAuthGetSessionBlock) completion {
[self launchUsing:anchor uiViewController:nil completion:completion];
}
- (void)launchUsing:(nullable ASPresentationAnchor) anchor
uiViewController:(nullable UIViewController *) vc
completion:(nullable AWSCognitoAuthGetSessionBlock) completion {
__block __weak NSOperation *weakGetSessionOperation;
NSOperation *getSessionOperation = [NSBlockOperation blockOperationWithBlock:^{
self.presentationAnchor = anchor;
[self prepareForSignIn:vc completion:completion];
if(weakGetSessionOperation.isCancelled){
[self dismissSafariViewControllerAndCompleteGetSession:nil error:self.getSessionError];
}
[self launchSignInVC:vc];
}];
weakGetSessionOperation = getSessionOperation;
[self.getSessionQueue addOperation:getSessionOperation];
}
#pragma mark get session
- (void)getSession:(AWSCognitoAuthGetSessionBlock) completion {
self.presentationAnchor = nil;
[self enqueueGetSession:nil completion:completion];
}
- (void)getSession:(UIViewController *) vc completion: (AWSCognitoAuthGetSessionBlock) completion {
self.presentationAnchor = nil;
[self enqueueGetSession:vc completion:completion];
}
- (void)getSessionWithWebUI: (ASPresentationAnchor) anchor
completion: (nullable AWSCognitoAuthGetSessionBlock) completion {
self.presentationAnchor = anchor;
[self enqueueGetSession:nil completion:completion];
}
/**
Adds another getSession operation to the serialized queue of getSession requests
*/
- (void)enqueueGetSession:(nullable UIViewController *) vc completion: (AWSCognitoAuthGetSessionBlock) completion {
__block __weak NSOperation *weakGetSessionOperation;
NSOperation *getSessionOperation = [NSBlockOperation blockOperationWithBlock:^{
[self getSessionInternal:vc completion:completion];
if(weakGetSessionOperation.isCancelled){
[self dismissSafariViewControllerAndCompleteGetSession:nil error:self.getSessionError];
}
}];
weakGetSessionOperation = getSessionOperation;
[self.getSessionQueue addOperation:getSessionOperation];
}
/**
Cleanup resources from the sign in attempt
*/
- (void) cleanupSignIn {
self.getSessionBlock = nil;
self.proofKey = nil;
self.state = nil;
self.proofKeyHash = nil;
self.pvc = nil;
self.responseData = nil;
}
- (void)prepareForSignIn:(UIViewController *) vc
completion:(AWSCognitoAuthGetSessionBlock) completion {
self.getSessionBlock = completion;
self.state = [[[NSUUID UUID] UUIDString] lowercaseString];
self.proofKey = [self generateRandom:32];
self.proofKeyHash = [self calculateSHA256Hash:self.proofKey];
self.pvc = vc;
}
/**
Launch the sign in ui on the provided viewcontroller
*/
- (void) launchSignInVC: (UIViewController *) vc {
NSString *suffix = @"";
if(self.authConfiguration.idpIdentifier || self.authConfiguration.identityProvider){
if(self.authConfiguration.idpIdentifier){
suffix = [NSString stringWithFormat:@"&idp_identifier=%@", self.authConfiguration.idpIdentifier];
} else {
suffix = [NSString stringWithFormat:@"&identity_provider=%@", self.authConfiguration.identityProvider];
}
}
if(self.authConfiguration.asfEnabled){
NSString *userContextEncoded = [AWSCognitoIdentityProviderASF userContextData:self.authConfiguration.userPoolId
username:@"unknown"
deviceId:[self asfDeviceId]
userPoolClientId:self.authConfiguration.appClientId];
NSString * userContext = [NSString stringWithFormat:@"&userContextData=%@",[self urlEncode:userContextEncoded]];
suffix = [suffix stringByAppendingString:userContext];
}
NSString *urlString = [NSString stringWithFormat:@"%@?response_type=code&client_id=%@&state=%@&redirect_uri=%@&scope=%@&code_challenge=%@&code_challenge_method=S256%@&%@",
self.authConfiguration.signInUri,
self.authConfiguration.appClientId,
self.state,
[self urlEncode:self.authConfiguration.signInRedirectUri],
[self urlEncode:[self normalizeScopes]],
self.proofKeyHash,
suffix,
[self getQueryStringSuffixForParameters: self.authConfiguration.signInUriQueryParameters]];
NSURL *url = [NSURL URLWithString:urlString];
if(@available(iOS 13.0, *)) {
if (self.presentationAnchor) {
[self launchASWebAuthenticationSession: url];
} else {
[self launchLegacySession:url withPresentingViewController:vc];
}
} else {
[self launchLegacySession:url withPresentingViewController:vc];
}
}
- (void)launchLegacySession:(NSURL *)url
withPresentingViewController:(UIViewController *)presentingViewController {
if (self.useSFAuthenticationSession) {
if (@available(iOS 11.0, *)) {
[self launchSFWebAuthenticationSession: url];
} else {
// Fallback on earlier versions
[self showSFSafariViewControllerForURL:url withPresentingViewController:presentingViewController];
}
} else {
[self showSFSafariViewControllerForURL:url withPresentingViewController:presentingViewController];
}
}
// SFAuthenticationSession was deprecated in iOS 12, but keeping it for flows without a presentationAnchor
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (void)launchSFWebAuthenticationSession:(NSURL *)hostedUIURL API_AVAILABLE(ios(11.0)) {
self.sfAuthenticationSessionAvailable = YES;
NSString *callbackURLScheme = [[self urlEncode:self.authConfiguration.signInRedirectUri] copy];
__weak AWSCognitoAuth *weakSelf = self;
self.sfAuthSession = [[SFAuthenticationSession alloc] initWithURL:hostedUIURL
callbackURLScheme:callbackURLScheme
completionHandler:^(NSURL * _Nullable url,
NSError * _Nullable error) {
__strong AWSCognitoAuth *strongSelf = weakSelf;
[strongSelf handleSignInCallbackWithURL:url error:error];
}];
[self.sfAuthSession start];
}
#pragma clang diagnostic pop
- (void)launchASWebAuthenticationSession:(NSURL *)hostedUIURL API_AVAILABLE(ios(13.0)) {
NSString *callbackURLString = [[self urlEncode:self.authConfiguration.signInRedirectUri] copy];
NSURL *callbackURL = [[NSURL alloc] initWithString:callbackURLString];
NSString *callbackURLScheme = callbackURL.scheme;
__weak AWSCognitoAuth *weakSelf = self;
self.asAuthSession = [[ASWebAuthenticationSession alloc] initWithURL:hostedUIURL
callbackURLScheme:callbackURLScheme
completionHandler:^(NSURL * _Nullable url,
NSError * _Nullable error) {
__strong AWSCognitoAuth *strongSelf = weakSelf;
[strongSelf handleSignInCallbackWithURL:url error:error];
}];
if (@available(iOS 13.0, *)) {
self.asAuthSession.prefersEphemeralWebBrowserSession = self.authConfiguration.isSignInPrivateSession;
self.asAuthSession.presentationContextProvider = self;
}
[self.asAuthSession start];
}
- (nonnull ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(nonnull ASWebAuthenticationSession *)session API_AVAILABLE(ios(13.0)) {
return self.presentationAnchor;
}
- (void)handleSignInCallbackWithURL:(NSURL * _Nullable) url
error:(NSError * _Nullable) error {
if (url) {
[self processURL:url forRedirection:NO];
} else {
[self dismissSafariViewControllerAndCompleteGetSession:nil error:error];
}
}
-(void)showSFSafariViewControllerForURL:(NSURL *)url
withPresentingViewController:(UIViewController *)presentingViewController{
SFSafariViewControllerConfiguration *configuration = [[SFSafariViewControllerConfiguration alloc] init];
configuration.entersReaderIfAvailable = NO;
self.svc = [[SFSafariViewController alloc] initWithURL:url configuration:configuration];
self.svc.delegate = self;
self.svc.modalPresentationStyle = UIModalPresentationPopover;
self.isProcessingSignIn = YES;
dispatch_async(dispatch_get_main_queue(), ^{
self.svc.presentationController.delegate = self;
__block UIViewController * sourceVC = presentingViewController;
if(!sourceVC){
if(!self.delegate){
[self dismissSafariViewControllerAndCompleteGetSession:nil error:[self getError:@"delegate must be set to a valid AWSCognitoAuthDelegate" code:AWSCognitoAuthClientInvalidAuthenticationDelegate]];
return;
} else {
sourceVC = [self.delegate getViewController];
}
}
[self setPopoverSource:self.svc source:sourceVC];
[sourceVC presentViewController:self.svc animated:NO completion:nil];
});
}
/**
* Configure source view for a modal popup view controller
*/
-(UIViewController *) setPopoverSource: (UIViewController *) popover source: (UIViewController *) source {
popover.popoverPresentationController.sourceView = source.view;
popover.popoverPresentationController.sourceRect = source.view.bounds;
[popover setPreferredContentSize:CGSizeMake(source.view.bounds.size.width/1.5,source.view.bounds.size.height/1.5)];
[popover.popoverPresentationController setPermittedArrowDirections:0];
return popover;
}
/**
Check keychain for valid session, if expired or not available, prompt end user via ui
*/
- (void)getSessionInternal: (nullable UIViewController *) vc completion: (AWSCognitoAuthGetSessionBlock) completion {
[self prepareForSignIn:vc completion:completion];
//check to see if we have valid tokens
NSString * username = [self currentUsername];
if(username){
__block NSString * keyChainNamespace = [self keyChainNamespaceClientId: [self currentUsername]];
NSString * expirationDateKey = [self keyChainKey:keyChainNamespace key:AWSCognitoAuthUserTokenExpiration];
NSString * expirationDate = self.keychain[expirationDateKey];
NSString * scopesKey = [self keyChainKey:keyChainNamespace key:AWSCognitoAuthUserScopes];
NSString * scopes = self.keychain[scopesKey];
if(expirationDate && scopes != nil && [scopes isEqualToString:[self normalizeScopes]]){
NSDate *expiration = [self dateFromString:expirationDate];
NSString * refreshToken = [self refreshTokenFromKeyChain:keyChainNamespace];
NSString * accessTokenKey = [self keyChainKey:keyChainNamespace key:AWSCognitoAuthUserAccessToken];
NSString * accessToken = self.keychain[accessTokenKey];
//if the session expires > 5 minutes return it.
if(expiration && [expiration compare:[NSDate dateWithTimeIntervalSinceNow:5 * 60]] == NSOrderedDescending && accessToken){
NSString * idTokenKey = [self keyChainKey:keyChainNamespace key:AWSCognitoAuthUserIdToken];
AWSCognitoAuthUserSession * session = [[AWSCognitoAuthUserSession alloc] initWithIdToken:self.keychain[idTokenKey]
accessToken:accessToken
refreshToken:refreshToken
expirationTime:expiration];
[self dismissSafariViewControllerAndCompleteGetSession:session error:nil];
return;
}
//else refresh it using the refresh token
else if(refreshToken){
NSString *url = [NSString stringWithFormat:@"%@",self.authConfiguration.tokensUri];
NSString *queryParameters = [self getQueryStringSuffixForParameters:self.authConfiguration.tokensUriQueryParameters];
NSString *body = [NSString stringWithFormat:@"grant_type=refresh_token&client_id=%@&refresh_token=%@",self.authConfiguration.appClientId, refreshToken];
if(queryParameters) {
body = [NSString stringWithFormat:@"%@&%@", body, queryParameters];
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[self addHeaders:request];
request.HTTPMethod = @"POST";
request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
forMode:NSDefaultRunLoopMode];
[connection start];
return;
}
}
}
//if we made it this far, we need the end user to authenticate
[self launchSignInVC: vc];
}
/**
Dismiss ui, invoke completion and cleanup a getSession call.
*/
- (void) dismissSafariViewControllerAndCompleteGetSession: (nullable AWSCognitoAuthUserSession *) userSession error:(nullable NSError *) error {
if(error){
[self setInternalGetSessionErrorAndCancelSignInOperations:error];
}
self.isProcessingSignIn = NO;
if (self.sfAuthenticationSessionAvailable) {
[self cleanUpAndCallGetSessionBlock:userSession error:error];
} else {
[self dismissSafariVC: ^{
[self cleanUpAndCallGetSessionBlock:userSession error:error];
}];
}
}
- (void) cleanUpAndCallGetSessionBlock: (nullable AWSCognitoAuthUserSession *) userSession error:(nullable NSError *) error {
AWSCognitoAuthGetSessionBlock getSessionBlock = self.getSessionBlock;
[self cleanupSignIn];
if(getSessionBlock){
getSessionBlock(userSession, error);
}
}
#pragma mark sign out
/**
Dismiss ui, invoke completion and cleanup a signOut call.
*/
- (void) dismissSafariViewControllerAndCompleteSignOut:(nullable NSError *) error {
if(error){
[self setInternalSignOutErrorAndCancelSignOutOperations:error];
}
self.isProcessingSignOut = NO;
if (self.sfAuthenticationSessionAvailable) {
[self cleanUpAndCallSignOutBlock:error];
} else {
[self dismissSafariVC: ^{
[self cleanUpAndCallSignOutBlock:error];
}];
}
}
- (void) cleanUpAndCallSignOutBlock:(nullable NSError *) error {
AWSCognitoAuthSignOutBlock signOutBlock = self.signOutBlock;
self.signOutBlock = nil;
if(signOutBlock){
signOutBlock(error);
}
}
- (void) signOut: (AWSCognitoAuthSignOutBlock) completion {
self.presentationAnchor = nil;
if(!self.delegate){
completion([self getError:@"delegate must be set to a valid AWSCognitoAuthDelegate" code:AWSCognitoAuthClientInvalidAuthenticationDelegate]);
}else {
[self signOut: [self.delegate getViewController] completion:completion];
}
}
- (void) signOut: (UIViewController *) vc completion: (AWSCognitoAuthSignOutBlock) completion {
self.presentationAnchor = nil;
[self enqueueSignOut:vc completion:completion];
}
- (void) signOutWithWebUI:(ASPresentationAnchor) anchor completion:(AWSCognitoAuthSignOutBlock) completion {
self.presentationAnchor = anchor;
[self enqueueSignOut:nil completion:completion];
}
- (void)enqueueSignOut:(nullable UIViewController *) vc
completion: (AWSCognitoAuthSignOutBlock) completion {
__block __weak NSOperation *weakSignOutOperation;
NSOperation *signOutOperation = [NSBlockOperation blockOperationWithBlock:^{
if(weakSignOutOperation.isCancelled){
completion(self.signOutError);
}
[self signOutInternal:vc completion:completion];
}];
weakSignOutOperation = signOutOperation;
[self.signOutQueue addOperation:signOutOperation];
}
- (NSString *)getQueryStringSuffixForParameters:(NSDictionary<NSString *, NSString *> *)queryParameters {
if (queryParameters.count > 0) {
NSString *queryString = @"";
for(NSString *key in queryParameters) {
NSString *value = [queryParameters objectForKey:key];
if(value) {
queryString = [NSString stringWithFormat:@"%@%@=%@&",queryString, key, value];
} else {
queryString = [NSString stringWithFormat:@"%@&", key];
}
}
return [queryString substringToIndex:[queryString length] - 1];
} else {
return @"";
}
}
/**
Display ui for signout
*/
- (void) signOutInternal:(UIViewController *) vc completion:(AWSCognitoAuthSignOutBlock) completion {
self.signOutBlock = completion;
NSString *urlString = [NSString stringWithFormat:@"%@?%@",
self.authConfiguration.signOutUri,
[self getQueryStringSuffixForParameters:self.authConfiguration.signOutUriQueryParameters]];
NSURL *url = [NSURL URLWithString:urlString];
if(@available(iOS 13.0, *)) {
if (self.presentationAnchor) {
[self launchASWebAuthenticationSessionForSignOut:url];
} else {
[self launchLegacySessionForSignOut:url withPresentingViewController:vc];
}
} else {
[self launchLegacySessionForSignOut:url withPresentingViewController:vc];
}
}
- (void)launchASWebAuthenticationSessionForSignOut:(NSURL *) url API_AVAILABLE(ios(13.0)) {
NSString *callbackURLString = [[self urlEncode:self.authConfiguration.signInRedirectUri] copy];
NSURL *callbackURL = [[NSURL alloc] initWithString:callbackURLString];
NSString *callbackURLScheme = callbackURL.scheme;
__weak AWSCognitoAuth *weakSelf = self;
self.asAuthSession = [[ASWebAuthenticationSession alloc] initWithURL:url
callbackURLScheme:callbackURLScheme
completionHandler:^(NSURL * _Nullable url,
NSError * _Nullable error) {
__strong AWSCognitoAuth *strongSelf = weakSelf;
if (url) {
[strongSelf processURL:url forRedirection:NO];
} else {
if (error.code != ASWebAuthenticationSessionErrorCodeCanceledLogin) {
[strongSelf signOutLocallyAndClearLastKnownUser];
}
[strongSelf dismissSafariViewControllerAndCompleteSignOut:error];
}
}];
if (@available(iOS 13.0, *)) {
self.asAuthSession.presentationContextProvider = self;
}
[self.asAuthSession start];
}
- (void)launchLegacySessionForSignOut:(NSURL *) url
withPresentingViewController:(UIViewController *) presentingViewController {
if (self.useSFAuthenticationSession) {
if (@available(iOS 11.0, *)) {
[self launchSFAuthenticationSessionForSignOut:url];
} else {
[self signOutSFSafariVC:presentingViewController url:url];
}
} else {
[self signOutSFSafariVC:presentingViewController url:url];
}
}
// SFAuthenticationSession was deprecated in iOS 12, but keeping it for flows without a presentationAnchor
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (void)launchSFAuthenticationSessionForSignOut:(NSURL *) url API_AVAILABLE(ios(11.0)) {
self.sfAuthenticationSessionAvailable = YES;
NSString *callbackURLScheme = [[self urlEncode:self.authConfiguration.signOutRedirectUri] copy];
__weak AWSCognitoAuth *weakSelf = self;
self.sfAuthSession = [[SFAuthenticationSession alloc] initWithURL:url
callbackURLScheme:callbackURLScheme
completionHandler:^(NSURL * _Nullable url,
NSError * _Nullable error) {
__strong AWSCognitoAuth *strongSelf = weakSelf;
if (url) {
[strongSelf processURL:url forRedirection:NO];
} else {
if (error.code != SFAuthenticationErrorCanceledLogin) {
[strongSelf signOutLocallyAndClearLastKnownUser];
}
[strongSelf dismissSafariViewControllerAndCompleteSignOut:error];
}
}];
[self.sfAuthSession start];
}
#pragma clang diagnostic pop
- (void)signOutSFSafariVC: (UIViewController *) vc
url:(NSURL *)url {
SFSafariViewControllerConfiguration *configuration = [[SFSafariViewControllerConfiguration alloc] init];
configuration.entersReaderIfAvailable = NO;
self.svc = [[SFSafariViewController alloc] initWithURL:url configuration:configuration];
self.svc.delegate = self;
self.svc.modalPresentationStyle = UIModalPresentationPopover;
self.isProcessingSignOut = YES;
dispatch_async(dispatch_get_main_queue(), ^{
[self setPopoverSource:self.svc source:vc];
[vc presentViewController:self.svc animated:NO completion:nil];
});
}
/**
Remove user session from keychain
*/
-(void) signOutLocally {
if([self currentUsername]){
NSArray *keys = self.keychain.allKeys;
NSString *keyChainPrefix = [[self keyChainNamespaceClientId:[self currentUsername]] stringByAppendingString:@"."];
for (NSString *key in keys) {
//clear tokens associated with this user
if([key hasPrefix:keyChainPrefix]){
[self.keychain removeItemForKey:key];
}
}
}
}
/**
Remove user session from keychain and clear last known username.
*/
-(void) signOutLocallyAndClearLastKnownUser{
[self signOutLocally];
[self clearLastKnownUser];
}
#pragma mark date conversion
/**
Obtain a date formatter for this format: yyyy-MM-dd'T'HH:mm:ss'Z'
*/
-(NSDateFormatter *) getDateFormatter {
static NSDateFormatter *_dateFormatter = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_dateFormatter = [NSDateFormatter new];
_dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
_dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
_dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss'Z'";
});
return _dateFormatter;
}
/**
Convert a string to date
*/
-(NSDate *) dateFromString:(NSString *)string {
return [[self getDateFormatter] dateFromString:string];
}
/**
Convert a string to date
*/
-(NSString *) stringValue: (NSDate*) date {
return [[self getDateFormatter] stringFromDate:date];
}
#pragma mark SFSafariViewController delegate
/*! @abstract Delegate callback called when the user taps the Done button. Upon this call, the view controller is dismissed modally. */
- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller {
NSError *error = [self getError:@"User cancelled operation" code:AWSCognitoAuthClientErrorUserCanceledOperation];
if(self.getSessionBlock){
[self setInternalGetSessionErrorAndCancelSignInOperations:error];
[self cleanUpAndCallGetSessionBlock:nil error:error];
} else {
[self setInternalSignOutErrorAndCancelSignOutOperations:error];
[self cleanUpAndCallSignOutBlock:error];
}
}
//handle user swipe down to dismiss the SafariViewController
- (void)presentationControllerDidDismiss:(UIPresentationController *) presentationController {
NSError *error = [self getError:@"User cancelled operation" code:AWSCognitoAuthClientErrorUserCanceledOperation];
if(self.getSessionBlock){
[self setInternalGetSessionErrorAndCancelSignInOperations:error];
[self cleanUpAndCallGetSessionBlock:nil error:error];
} else {
[self setInternalSignOutErrorAndCancelSignOutOperations:error];
[self cleanUpAndCallSignOutBlock:error];
}
}
- (void)setInternalSignOutErrorAndCancelSignOutOperations:(NSError *)error {
self.signOutError = error;
[self.signOutQueue cancelAllOperations];
}
- (void)setInternalGetSessionErrorAndCancelSignInOperations:(NSError *)error {
self.getSessionError = error;
[self.getSessionQueue cancelAllOperations];
}
/*! @abstract Invoked when the initial URL load is complete.
@param didLoadSuccessfully YES if loading completed successfully, NO if loading failed.
@discussion This method is invoked when SFSafariViewController completes the loading of the URL that you pass
to its initializer. It is not invoked for any subsequent page loads in the same SFSafariViewController instance.
*/
- (void)safariViewController:(SFSafariViewController *)controller didCompleteInitialLoad:(BOOL)didLoadSuccessfully {
if(!didLoadSuccessfully && !self.isHandlingRedirection && !(self.isProcessingSignOut || self.isProcessingSignIn)){
NSError *error = [self getError:@"Loading page failed" code:AWSCognitoAuthClientErrorLoadingPageFailed];
if(self.getSessionBlock){
[self dismissSafariViewControllerAndCompleteGetSession:nil error:error];
}else if(self.signOutBlock){
[self dismissSafariViewControllerAndCompleteSignOut:error];
}
}
}
#pragma PKCE
/**
Generate a random number of size bytes and base64 encode it with a url safe encoding.
*/
-(NSString *) generateRandom: (int) size {
NSMutableData *data = [NSMutableData dataWithLength:size];
int result = SecRandomCopyBytes(kSecRandomDefault, size, data.mutableBytes);
if(result){
return nil;
}
return [self urlSafeBase64:[data base64EncodedStringWithOptions:0]];
}
/**
Calculate a SHA256 Hash of a string and base64 encode it with a url safe encoding.
*/
-(NSString *) calculateSHA256Hash: (NSString *) string {
NSMutableData *hashOutput = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
if(CC_SHA256([[[string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES] mutableCopy] mutableBytes], (CC_LONG)[string lengthOfBytesUsingEncoding:NSASCIIStringEncoding], hashOutput.mutableBytes)){
return [self urlSafeBase64:[hashOutput base64EncodedStringWithOptions:0]];
}
return nil;
}
/**
Make a base64 encoded string url safe
*/
-(NSString *) urlSafeBase64: (NSString *) string {
return [[[string stringByReplacingOccurrencesOfString:@"/" withString:@"_"] stringByReplacingOccurrencesOfString:@"+" withString:@"-"] stringByReplacingOccurrencesOfString:@"=" withString:@""];
}
/**
Make a string url safe
**/
- (NSString *) urlEncode: (NSString *) stringToEncode {
return [stringToEncode stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
return [self processURL:url forRedirection:YES];
}
- (BOOL)processURL:(NSURL *)url forRedirection:(BOOL)isProcessingRedirection {
NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url
resolvingAgainstBaseURL:NO];
NSArray<NSURLQueryItem *>* queryItems = [urlComponents queryItems];
NSMutableDictionary *queryItemsDict = nil;
if(queryItems) {
queryItemsDict = [NSMutableDictionary new];
for(NSURLQueryItem * queryItem in queryItems){
[queryItemsDict setObject:queryItem.value forKey:queryItem.name];
}
}
NSString *urlLowerCaseString = [[url absoluteString] lowercaseString];
NSString *signInRedirectLowerCaseString = [self.authConfiguration.signInRedirectUri lowercaseString];
NSString *signOutRedirectLowerCaseString = [self.authConfiguration.signOutRedirectUri lowercaseString];
if([urlLowerCaseString hasPrefix:signInRedirectLowerCaseString] && queryItemsDict[@"state"]) {
if(queryItemsDict[@"code"]){
//if state doesn't match, abort
if(![self.state isEqualToString:queryItemsDict[@"state"]]){
[self dismissSafariViewControllerAndCompleteGetSession:nil error:[self getError:@"State code did not match request" code: AWSCognitoAuthClientErrorSecurityFailed]];
return YES;
} else {
//continue with authorization code request
NSString * code = queryItemsDict[@"code"];
if(code){
// If we are processing this request on behalf of a redirection request from SFSafariViewController, then
// set a flag to prevent us from interpreting a "NO" callback to `safariViewController:didCompleteInitialLoad:`
// as an error. We will clear this flag in `connectionDidFinishLoading:` after the auth token request has
// completed
if (isProcessingRedirection) {
self.isHandlingRedirection = YES;
}
NSString *queryParameters = [self getQueryStringSuffixForParameters:self.authConfiguration.tokensUriQueryParameters];
NSString *url = [NSString stringWithFormat:@"%@",self.authConfiguration.tokensUri];
NSString *body = [NSString stringWithFormat:@"grant_type=authorization_code&client_id=%@&code=%@&redirect_uri=%@&code_verifier=%@",
self.authConfiguration.appClientId, code, self.authConfiguration.signInRedirectUri, self.proofKey];
if(queryParameters) {
body = [NSString stringWithFormat:@"%@&%@", body, queryParameters];
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
request.HTTPMethod = @"POST";
request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
[self addHeaders:request];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
forMode:NSDefaultRunLoopMode];
[connection start];
return YES;
}
}
}else if(queryItemsDict[@"error"]){
NSString *error = queryItemsDict[@"error"];
NSString *errorDescription = queryItemsDict[@"error_description"];
if(errorDescription){
error = [NSString stringWithFormat:@"%@: %@", error, errorDescription];
}
[self dismissSafariViewControllerAndCompleteGetSession:nil error:[self getError:error code: AWSCognitoAuthClientErrorBadRequest]];
return YES;
}
} else if([urlLowerCaseString hasPrefix:signOutRedirectLowerCaseString]){
if(queryItemsDict[@"error"]){
NSString *error = queryItemsDict[@"error"];
NSString *errorDescription = queryItemsDict[@"error_description"];
if(errorDescription){
error = [NSString stringWithFormat:@"%@: %@", error, errorDescription];
}
[self signOutLocallyAndClearLastKnownUser];
[self dismissSafariViewControllerAndCompleteSignOut:[self getError:error code:AWSCognitoAuthClientErrorBadRequest]];
}else{
[self signOutLocallyAndClearLastKnownUser];
[self dismissSafariViewControllerAndCompleteSignOut:nil];
}
return YES;
}
return NO;
}
#pragma mark HTTP header modification
/**
Add authorization and User-Agent header as appropriate.
*/
-(void) addHeaders: (NSMutableURLRequest *) request {
if(self.authConfiguration.appClientSecret){
NSString* value = [[[NSString stringWithFormat:@"%@:%@", self.authConfiguration.appClientId, self.authConfiguration.appClientSecret] dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
value = [NSString stringWithFormat: @"Basic %@", value];
[request setValue:value forHTTPHeaderField:@"Authorization"];
}
[request setValue: [self fetchBaseUserAgent] forHTTPHeaderField:@"User-Agent"];
}
/**
Dismiss and reap the safari view controller
*/
-(void) dismissSafariVC: (void (^)(void)) dismissBlock {
dispatch_async(dispatch_get_main_queue(), ^{
if(self.svc){
[self.svc dismissViewControllerAnimated:NO completion:^{
dismissBlock();
//clean up vc
self.svc = nil;
}];
} else {
dismissBlock();
}
});
}
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
self.responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
self.isHandlingRedirection = NO;
NSError * error;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&error];
if(error){
[self dismissSafariViewControllerAndCompleteGetSession:nil error:[self getError:[error description] code:AWSCognitoAuthClientErrorUnknown]];
return;
}
else if(result[@"error"]){
//refresh token has expired, switch to interactive auth
if([@"invalid_grant" isEqualToString:result[@"error"]]){
if (![self.delegate respondsToSelector:@selector(shouldLaunchSignInVCIfRefreshTokenIsExpired)]) {
[self launchSignInVC:self.pvc];
}else {
BOOL present = [self.delegate shouldLaunchSignInVCIfRefreshTokenIsExpired];
if (present) {
[self launchSignInVC:self.pvc];
}else {
[self dismissSafariViewControllerAndCompleteGetSession:nil error:[self getError:result[@"error"] code:AWSCognitoAuthClientErrorExpiredRefreshToken]];
}
}
}else {
[self dismissSafariViewControllerAndCompleteGetSession:nil error:[self getError:result[@"error"] code:AWSCognitoAuthClientErrorUnknown]];
}