-
Notifications
You must be signed in to change notification settings - Fork 448
/
Copy pathRNAppAuth.m
757 lines (684 loc) · 43.2 KB
/
RNAppAuth.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
#import "RNAppAuth.h"
#if __has_include(<AppAuth/AppAuth.h>)
#import <AppAuth/AppAuth.h>
#else
#import "AppAuth.h"
#endif
#import <React/RCTLog.h>
#import <React/RCTConvert.h>
#import "RNAppAuthAuthorizationFlowManager.h"
@interface RNAppAuth()<RNAppAuthAuthorizationFlowManagerDelegate> {
id<OIDExternalUserAgentSession> _currentSession;
}
@end
@implementation RNAppAuth
-(BOOL)resumeExternalUserAgentFlowWithURL:(NSURL *)url {
return [_currentSession resumeExternalUserAgentFlowWithURL:url];
}
- (dispatch_queue_t)methodQueue
{
return dispatch_get_main_queue();
}
UIBackgroundTaskIdentifier rnAppAuthTaskId;
/*! @brief Number of random bytes generated for the @ state.
*/
static NSUInteger const kStateSizeBytes = 32;
/*! @brief Number of random bytes generated for the @ codeVerifier.
*/
static NSUInteger const kCodeVerifierBytes = 32;
RCT_EXPORT_MODULE()
RCT_REMAP_METHOD(register,
issuer: (NSString *) issuer
redirectUrls: (NSArray *) redirectUrls
responseTypes: (NSArray *) responseTypes
grantTypes: (NSArray *) grantTypes
subjectType: (NSString *) subjectType
tokenEndpointAuthMethod: (NSString *) tokenEndpointAuthMethod
additionalParameters: (NSDictionary *_Nullable) additionalParameters
serviceConfiguration: (NSDictionary *_Nullable) serviceConfiguration
connectionTimeoutSeconds: (double) connectionTimeoutSeconds
additionalHeaders: (NSDictionary *_Nullable) additionalHeaders
resolve: (RCTPromiseResolveBlock) resolve
reject: (RCTPromiseRejectBlock) reject)
{
[self configureUrlSession:additionalHeaders sessionTimeout:connectionTimeoutSeconds];
// if we have manually provided configuration, we can use it and skip the OIDC well-known discovery endpoint call
if (serviceConfiguration) {
OIDServiceConfiguration *configuration = [self createServiceConfiguration:serviceConfiguration];
[self registerWithConfiguration: configuration
redirectUrls: redirectUrls
responseTypes: responseTypes
grantTypes: grantTypes
subjectType: subjectType
tokenEndpointAuthMethod: tokenEndpointAuthMethod
additionalParameters: additionalParameters
resolve: resolve
reject: reject];
} else {
[OIDAuthorizationService discoverServiceConfigurationForIssuer:[NSURL URLWithString:issuer]
completion:^(OIDServiceConfiguration *_Nullable configuration, NSError *_Nullable error) {
if (!configuration) {
reject(@"service_configuration_fetch_error", [error localizedDescription], error);
return;
}
[self registerWithConfiguration: configuration
redirectUrls: redirectUrls
responseTypes: responseTypes
grantTypes: grantTypes
subjectType: subjectType
tokenEndpointAuthMethod: tokenEndpointAuthMethod
additionalParameters: additionalParameters
resolve: resolve
reject: reject];
}];
}
} // end RCT_REMAP_METHOD(register,
RCT_REMAP_METHOD(authorize,
issuer: (NSString *) issuer
redirectUrl: (NSString *) redirectUrl
clientId: (NSString *) clientId
clientSecret: (NSString *) clientSecret
scopes: (NSArray *) scopes
additionalParameters: (NSDictionary *_Nullable) additionalParameters
serviceConfiguration: (NSDictionary *_Nullable) serviceConfiguration
skipCodeExchange: (BOOL) skipCodeExchange
connectionTimeoutSeconds: (double) connectionTimeoutSeconds
additionalHeaders: (NSDictionary *_Nullable) additionalHeaders
useNonce: (BOOL *) useNonce
usePKCE: (BOOL *) usePKCE
iosCustomBrowser: (NSString *) iosCustomBrowser
prefersEphemeralSession: (BOOL *) prefersEphemeralSession
resolve: (RCTPromiseResolveBlock) resolve
reject: (RCTPromiseRejectBlock) reject)
{
[self configureUrlSession:additionalHeaders sessionTimeout:connectionTimeoutSeconds];
// if we have manually provided configuration, we can use it and skip the OIDC well-known discovery endpoint call
if (serviceConfiguration) {
OIDServiceConfiguration *configuration = [self createServiceConfiguration:serviceConfiguration];
[self authorizeWithConfiguration: configuration
redirectUrl: redirectUrl
clientId: clientId
clientSecret: clientSecret
scopes: scopes
useNonce: useNonce
usePKCE: usePKCE
additionalParameters: additionalParameters
skipCodeExchange: skipCodeExchange
iosCustomBrowser: iosCustomBrowser
prefersEphemeralSession: prefersEphemeralSession
resolve: resolve
reject: reject];
} else {
[OIDAuthorizationService discoverServiceConfigurationForIssuer:[NSURL URLWithString:issuer]
completion:^(OIDServiceConfiguration *_Nullable configuration, NSError *_Nullable error) {
if (!configuration) {
reject(@"service_configuration_fetch_error", [error localizedDescription], error);
return;
}
[self authorizeWithConfiguration: configuration
redirectUrl: redirectUrl
clientId: clientId
clientSecret: clientSecret
scopes: scopes
useNonce: useNonce
usePKCE: usePKCE
additionalParameters: additionalParameters
skipCodeExchange: skipCodeExchange
iosCustomBrowser: iosCustomBrowser
prefersEphemeralSession: prefersEphemeralSession
resolve: resolve
reject: reject];
}];
}
} // end RCT_REMAP_METHOD(authorize,
RCT_REMAP_METHOD(refresh,
issuer: (NSString *) issuer
redirectUrl: (NSString *) redirectUrl
clientId: (NSString *) clientId
clientSecret: (NSString *) clientSecret
refreshToken: (NSString *) refreshToken
scopes: (NSArray *) scopes
additionalParameters: (NSDictionary *_Nullable) additionalParameters
serviceConfiguration: (NSDictionary *_Nullable) serviceConfiguration
connectionTimeoutSeconds: (double) connectionTimeoutSeconds
additionalHeaders: (NSDictionary *_Nullable) additionalHeaders
iosCustomBrowser: (NSString *) iosCustomBrowser
resolve:(RCTPromiseResolveBlock) resolve
reject: (RCTPromiseRejectBlock) reject)
{
[self configureUrlSession:additionalHeaders sessionTimeout:connectionTimeoutSeconds];
// if we have manually provided configuration, we can use it and skip the OIDC well-known discovery endpoint call
if (serviceConfiguration) {
OIDServiceConfiguration *configuration = [self createServiceConfiguration:serviceConfiguration];
[self refreshWithConfiguration: configuration
redirectUrl: redirectUrl
clientId: clientId
clientSecret: clientSecret
refreshToken: refreshToken
scopes: scopes
additionalParameters: additionalParameters
resolve: resolve
reject: reject];
} else {
// otherwise hit up the discovery endpoint
[OIDAuthorizationService discoverServiceConfigurationForIssuer:[NSURL URLWithString:issuer]
completion:^(OIDServiceConfiguration *_Nullable configuration, NSError *_Nullable error) {
if (!configuration) {
reject(@"service_configuration_fetch_error", [error localizedDescription], error);
return;
}
[self refreshWithConfiguration: configuration
redirectUrl: redirectUrl
clientId: clientId
clientSecret: clientSecret
refreshToken: refreshToken
scopes: scopes
additionalParameters: additionalParameters
resolve: resolve
reject: reject];
}];
}
} // end RCT_REMAP_METHOD(refresh,
RCT_REMAP_METHOD(logout,
issuer: (NSString *) issuer
idTokenHint: (NSString *) idTokenHint
postLogoutRedirectURL: (NSString *) postLogoutRedirectURL
serviceConfiguration: (NSDictionary *_Nullable) serviceConfiguration
additionalParameters: (NSDictionary *_Nullable) additionalParameters
iosCustomBrowser: (NSString *) iosCustomBrowser
prefersEphemeralSession: (BOOL *) prefersEphemeralSession
resolve:(RCTPromiseResolveBlock) resolve
reject: (RCTPromiseRejectBlock) reject)
{
if (serviceConfiguration) {
OIDServiceConfiguration *configuration = [self createServiceConfiguration:serviceConfiguration];
[self endSessionWithConfiguration: configuration
idTokenHint: idTokenHint
postLogoutRedirectURL: postLogoutRedirectURL
additionalParameters: additionalParameters
iosCustomBrowser: iosCustomBrowser
prefersEphemeralSession: prefersEphemeralSession
resolve: resolve
reject: reject];
} else {
[OIDAuthorizationService discoverServiceConfigurationForIssuer:[NSURL URLWithString:issuer]
completion:^(OIDServiceConfiguration *_Nullable configuration, NSError *_Nullable error) {
if (!configuration) {
reject(@"service_configuration_fetch_error", [error localizedDescription], error);
return;
}
[self endSessionWithConfiguration: configuration
idTokenHint: idTokenHint
postLogoutRedirectURL: postLogoutRedirectURL
additionalParameters: additionalParameters
iosCustomBrowser: iosCustomBrowser
prefersEphemeralSession: prefersEphemeralSession
resolve: resolve
reject: reject];
}];
}
} // end RCT_REMAP_METHOD(logout,
/*
* Create a OIDServiceConfiguration from passed serviceConfiguration dictionary
*/
- (OIDServiceConfiguration *) createServiceConfiguration: (NSDictionary *) serviceConfiguration {
NSURL *authorizationEndpoint = [NSURL URLWithString: [serviceConfiguration objectForKey:@"authorizationEndpoint"]];
NSURL *tokenEndpoint = [NSURL URLWithString: [serviceConfiguration objectForKey:@"tokenEndpoint"]];
NSURL *registrationEndpoint = [NSURL URLWithString: [serviceConfiguration objectForKey:@"registrationEndpoint"]];
NSURL *endSessionEndpoint = [NSURL URLWithString: [serviceConfiguration objectForKey:@"endSessionEndpoint"]];
OIDServiceConfiguration *configuration =
[[OIDServiceConfiguration alloc]
initWithAuthorizationEndpoint:authorizationEndpoint
tokenEndpoint:tokenEndpoint
issuer:nil
registrationEndpoint:registrationEndpoint
endSessionEndpoint:endSessionEndpoint];
return configuration;
}
+ (nullable NSString *)generateCodeVerifier {
return [OIDTokenUtilities randomURLSafeStringWithSize:kCodeVerifierBytes];
}
+ (nullable NSString *)generateState {
return [OIDTokenUtilities randomURLSafeStringWithSize:kStateSizeBytes];
}
+ (nullable NSString *)codeChallengeS256ForVerifier:(NSString *)codeVerifier {
if (!codeVerifier) {
return nil;
}
// generates the code_challenge per spec https://tools.ietf.org/html/rfc7636#section-4.2
// code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))
// NB. the ASCII conversion on the code_verifier entropy was done at time of generation.
NSData *sha256Verifier = [OIDTokenUtilities sha256:codeVerifier];
return [OIDTokenUtilities encodeBase64urlNoPadding:sha256Verifier];
}
/*
* Perform dynamic client registration with provided OIDServiceConfiguration
*/
- (void)registerWithConfiguration: (OIDServiceConfiguration *) configuration
redirectUrls: (NSArray *) redirectUrlStrings
responseTypes: (NSArray *) responseTypes
grantTypes: (NSArray *) grantTypes
subjectType: (NSString *) subjectType
tokenEndpointAuthMethod: (NSString *) tokenEndpointAuthMethod
additionalParameters: (NSDictionary *_Nullable) additionalParameters
resolve: (RCTPromiseResolveBlock) resolve
reject: (RCTPromiseRejectBlock) reject
{
NSMutableArray<NSURL *> *redirectUrls = [NSMutableArray arrayWithCapacity:[redirectUrlStrings count]];
for (NSString *urlString in redirectUrlStrings) {
[redirectUrls addObject:[NSURL URLWithString:urlString]];
}
OIDRegistrationRequest *request =
[[OIDRegistrationRequest alloc] initWithConfiguration:configuration
redirectURIs:redirectUrls
responseTypes:responseTypes
grantTypes:grantTypes
subjectType:subjectType
tokenEndpointAuthMethod:tokenEndpointAuthMethod
additionalParameters:additionalParameters];
[OIDAuthorizationService performRegistrationRequest:request
completion:^(OIDRegistrationResponse *_Nullable response,
NSError *_Nullable error) {
if (response) {
resolve([self formatRegistrationResponse:response]);
} else {
reject([self getErrorCode: error defaultCode:@"registration_failed"],
[self getErrorMessage: error], error);
}
}];
}
/*
* Authorize a user in exchange for a token with provided OIDServiceConfiguration
*/
- (void)authorizeWithConfiguration: (OIDServiceConfiguration *) configuration
redirectUrl: (NSString *) redirectUrl
clientId: (NSString *) clientId
clientSecret: (NSString *) clientSecret
scopes: (NSArray *) scopes
useNonce: (BOOL *) useNonce
usePKCE: (BOOL *) usePKCE
additionalParameters: (NSDictionary *_Nullable) additionalParameters
skipCodeExchange: (BOOL) skipCodeExchange
iosCustomBrowser: (NSString *) iosCustomBrowser
prefersEphemeralSession: (BOOL *) prefersEphemeralSession
resolve: (RCTPromiseResolveBlock) resolve
reject: (RCTPromiseRejectBlock) reject
{
NSString *codeVerifier = usePKCE ? [[self class] generateCodeVerifier] : nil;
NSString *codeChallenge = usePKCE ? [[self class] codeChallengeS256ForVerifier:codeVerifier] : nil;
NSString *nonce = useNonce ? additionalParameters[@"nonce"]? additionalParameters[@"nonce"]: [[self class] generateState] : nil ;
// builds authentication request
OIDAuthorizationRequest *request =
[[OIDAuthorizationRequest alloc] initWithConfiguration:configuration
clientId:clientId
clientSecret:clientSecret
scope:[OIDScopeUtilities scopesWithArray:scopes]
redirectURL:[NSURL URLWithString:redirectUrl]
responseType:OIDResponseTypeCode
state: additionalParameters[@"state"] ? additionalParameters[@"state"] : [[self class] generateState]
nonce:nonce
codeVerifier:codeVerifier
codeChallenge:codeChallenge
codeChallengeMethod: usePKCE ? OIDOAuthorizationRequestCodeChallengeMethodS256 : nil
additionalParameters:additionalParameters];
// performs authentication request
id<UIApplicationDelegate, RNAppAuthAuthorizationFlowManager> appDelegate = (id<UIApplicationDelegate, RNAppAuthAuthorizationFlowManager>)[UIApplication sharedApplication].delegate;
if (![[appDelegate class] conformsToProtocol:@protocol(RNAppAuthAuthorizationFlowManager)]) {
[NSException raise:@"RNAppAuth Missing protocol conformance"
format:@"%@ does not conform to RNAppAuthAuthorizationFlowManager", appDelegate];
}
appDelegate.authorizationFlowManagerDelegate = self;
__weak typeof(self) weakSelf = self;
rnAppAuthTaskId = [UIApplication.sharedApplication beginBackgroundTaskWithExpirationHandler:^{
[UIApplication.sharedApplication endBackgroundTask:rnAppAuthTaskId];
rnAppAuthTaskId = UIBackgroundTaskInvalid;
}];
UIViewController *presentingViewController = appDelegate.window.rootViewController.view.window ? appDelegate.window.rootViewController : appDelegate.window.rootViewController.presentedViewController;
#if TARGET_OS_MACCATALYST
id<OIDExternalUserAgent> externalUserAgent = nil;
#elif TARGET_OS_IOS
id<OIDExternalUserAgent> externalUserAgent = iosCustomBrowser != nil ? [self getCustomBrowser: iosCustomBrowser] : nil;
#endif
OIDAuthorizationCallback callback = ^(OIDAuthorizationResponse *_Nullable authorizationResponse, NSError *_Nullable error) {
typeof(self) strongSelf = weakSelf;
strongSelf->_currentSession = nil;
[UIApplication.sharedApplication endBackgroundTask:rnAppAuthTaskId];
rnAppAuthTaskId = UIBackgroundTaskInvalid;
if (authorizationResponse) {
resolve([self formatAuthorizationResponse:authorizationResponse withCodeVerifier:codeVerifier]);
} else {
reject([self getErrorCode: error defaultCode:@"authentication_failed"],
[self getErrorMessage: error], error);
}
};
if (skipCodeExchange) {
if(externalUserAgent != nil) {
_currentSession = [OIDAuthorizationService presentAuthorizationRequest:request
externalUserAgent:externalUserAgent
callback:callback];
} else {
if (@available(iOS 13, *)) {
_currentSession = [OIDAuthorizationService presentAuthorizationRequest:request
presentingViewController:presentingViewController
prefersEphemeralSession:prefersEphemeralSession
callback:callback];
} else {
_currentSession = [OIDAuthorizationService presentAuthorizationRequest:request
presentingViewController:presentingViewController
callback:callback];
}
}
} else {
OIDAuthStateAuthorizationCallback callback = ^(
OIDAuthState *_Nullable authState,
NSError *_Nullable error
) {
typeof(self) strongSelf = weakSelf;
strongSelf->_currentSession = nil;
[UIApplication.sharedApplication endBackgroundTask:rnAppAuthTaskId];
rnAppAuthTaskId = UIBackgroundTaskInvalid;
if (authState) {
resolve([self formatResponse:authState.lastTokenResponse
withAuthResponse:authState.lastAuthorizationResponse]);
} else {
reject([self getErrorCode: error defaultCode:@"authentication_failed"],
[self getErrorMessage: error], error);
}
};
if(externalUserAgent != nil) {
_currentSession = [OIDAuthState authStateByPresentingAuthorizationRequest:request
externalUserAgent:externalUserAgent
callback:callback];
} else {
if (@available(iOS 13, *)) {
_currentSession = [OIDAuthState authStateByPresentingAuthorizationRequest:request
presentingViewController:presentingViewController
prefersEphemeralSession:prefersEphemeralSession
callback:callback];
} else {
_currentSession = [OIDAuthState authStateByPresentingAuthorizationRequest:request
presentingViewController:presentingViewController
callback:callback];
}
}
}
}
/*
* Refresh a token with provided OIDServiceConfiguration
*/
- (void)refreshWithConfiguration: (OIDServiceConfiguration *)configuration
redirectUrl: (NSString *) redirectUrl
clientId: (NSString *) clientId
clientSecret: (NSString *) clientSecret
refreshToken: (NSString *) refreshToken
scopes: (NSArray *) scopes
additionalParameters: (NSDictionary *_Nullable) additionalParameters
resolve:(RCTPromiseResolveBlock) resolve
reject: (RCTPromiseRejectBlock) reject {
OIDTokenRequest *tokenRefreshRequest =
[[OIDTokenRequest alloc] initWithConfiguration:configuration
grantType:@"refresh_token"
authorizationCode:nil
redirectURL:[NSURL URLWithString:redirectUrl]
clientID:clientId
clientSecret:clientSecret
scopes:scopes
refreshToken:refreshToken
codeVerifier:nil
additionalParameters:additionalParameters];
[OIDAuthorizationService performTokenRequest:tokenRefreshRequest
callback:^(OIDTokenResponse *_Nullable response,
NSError *_Nullable error) {
if (response) {
resolve([self formatResponse:response]);
} else {
reject([self getErrorCode: error defaultCode:@"token_refresh_failed"],
[self getErrorMessage: error], error);
}
}];
}
- (void)endSessionWithConfiguration: (OIDServiceConfiguration *) configuration
idTokenHint: (NSString *) idTokenHint
postLogoutRedirectURL: (NSString *) postLogoutRedirectURL
additionalParameters: (NSDictionary *_Nullable) additionalParameters
iosCustomBrowser: (NSString *) iosCustomBrowser
prefersEphemeralSession: (BOOL *) prefersEphemeralSession
resolve: (RCTPromiseResolveBlock) resolve
reject: (RCTPromiseRejectBlock) reject {
OIDEndSessionRequest *endSessionRequest =
[[OIDEndSessionRequest alloc] initWithConfiguration: configuration
idTokenHint: idTokenHint
postLogoutRedirectURL: [NSURL URLWithString:postLogoutRedirectURL]
additionalParameters: additionalParameters];
id<UIApplicationDelegate, RNAppAuthAuthorizationFlowManager> appDelegate = (id<UIApplicationDelegate, RNAppAuthAuthorizationFlowManager>)[UIApplication sharedApplication].delegate;
if (![[appDelegate class] conformsToProtocol:@protocol(RNAppAuthAuthorizationFlowManager)]) {
[NSException raise:@"RNAppAuth Missing protocol conformance"
format:@"%@ does not conform to RNAppAuthAuthorizationFlowManager", appDelegate];
}
appDelegate.authorizationFlowManagerDelegate = self;
__weak typeof(self) weakSelf = self;
rnAppAuthTaskId = [UIApplication.sharedApplication beginBackgroundTaskWithExpirationHandler:^{
[UIApplication.sharedApplication endBackgroundTask:rnAppAuthTaskId];
rnAppAuthTaskId = UIBackgroundTaskInvalid;
}];
UIViewController *presentingViewController = appDelegate.window.rootViewController.view.window ? appDelegate.window.rootViewController : appDelegate.window.rootViewController.presentedViewController;
#if TARGET_OS_MACCATALYST
id<OIDExternalUserAgent> externalUserAgent = nil;
#elif TARGET_OS_IOS
id<OIDExternalUserAgent> externalUserAgent = iosCustomBrowser != nil ? [self getCustomBrowser: iosCustomBrowser] : [self getExternalUserAgentWithPresentingViewController:presentingViewController
prefersEphemeralSession:prefersEphemeralSession];
#endif
_currentSession = [OIDAuthorizationService presentEndSessionRequest: endSessionRequest
externalUserAgent: externalUserAgent
callback: ^(OIDEndSessionResponse *_Nullable response, NSError *_Nullable error) {
typeof(self) strongSelf = weakSelf;
strongSelf->_currentSession = nil;
[UIApplication.sharedApplication endBackgroundTask:rnAppAuthTaskId];
rnAppAuthTaskId = UIBackgroundTaskInvalid;
if (response) {
resolve([self formatEndSessionResponse:response]);
} else {
reject([self getErrorCode: error defaultCode:@"end_session_failed"],
[self getErrorMessage: error], error);
}
}];
}
- (void)configureUrlSession: (NSDictionary*) headers sessionTimeout: (double) sessionTimeout{
NSURLSessionConfiguration* configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
if (headers != nil) {
configuration.HTTPAdditionalHeaders = headers;
}
configuration.timeoutIntervalForRequest = sessionTimeout;
NSURLSession* session = [NSURLSession sessionWithConfiguration:configuration];
[OIDURLSessionProvider setSession:session];
}
/*
* Take raw OIDAuthorizationResponse and turn it to response format to pass to JavaScript caller
*/
- (NSDictionary *)formatAuthorizationResponse: (OIDAuthorizationResponse *) response withCodeVerifier: (NSString *) codeVerifier {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.timeZone = [NSTimeZone timeZoneWithAbbreviation: @"UTC"];
[dateFormat setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
if (codeVerifier == nil) {
return @{@"authorizationCode": response.authorizationCode ? response.authorizationCode : @"",
@"state": response.state ? response.state : @"",
@"accessToken": response.accessToken ? response.accessToken : @"",
@"accessTokenExpirationDate": response.accessTokenExpirationDate ? [dateFormat stringFromDate:response.accessTokenExpirationDate] : @"",
@"tokenType": response.tokenType ? response.tokenType : @"",
@"idToken": response.idToken ? response.idToken : @"",
@"scopes": response.scope ? [response.scope componentsSeparatedByString:@" "] : [NSArray new],
@"additionalParameters": response.additionalParameters,
};
} else {
return @{@"authorizationCode": response.authorizationCode ? response.authorizationCode : @"",
@"state": response.state ? response.state : @"",
@"accessToken": response.accessToken ? response.accessToken : @"",
@"accessTokenExpirationDate": response.accessTokenExpirationDate ? [dateFormat stringFromDate:response.accessTokenExpirationDate] : @"",
@"tokenType": response.tokenType ? response.tokenType : @"",
@"idToken": response.idToken ? response.idToken : @"",
@"scopes": response.scope ? [response.scope componentsSeparatedByString:@" "] : [NSArray new],
@"additionalParameters": response.additionalParameters,
@"codeVerifier": codeVerifier
};
}
}
/*
* Take raw OIDTokenResponse and turn it to a token response format to pass to JavaScript caller
*/
- (NSDictionary*)formatResponse: (OIDTokenResponse*) response {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.timeZone = [NSTimeZone timeZoneWithAbbreviation: @"UTC"];
[dateFormat setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
return @{@"accessToken": response.accessToken ? response.accessToken : @"",
@"accessTokenExpirationDate": response.accessTokenExpirationDate ? [dateFormat stringFromDate:response.accessTokenExpirationDate] : @"",
@"additionalParameters": response.additionalParameters,
@"idToken": response.idToken ? response.idToken : @"",
@"refreshToken": response.refreshToken ? response.refreshToken : @"",
@"tokenType": response.tokenType ? response.tokenType : @"",
};
}
/*
* Take raw OIDTokenResponse and additional paramaeters from an OIDAuthorizationResponse
* and turn them into an extended token response format to pass to JavaScript caller
*/
- (NSDictionary*)formatResponse: (OIDTokenResponse*) response
withAuthResponse:(OIDAuthorizationResponse*) authResponse {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.timeZone = [NSTimeZone timeZoneWithAbbreviation: @"UTC"];
[dateFormat setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
return @{@"accessToken": response.accessToken ? response.accessToken : @"",
@"accessTokenExpirationDate": response.accessTokenExpirationDate ? [dateFormat stringFromDate:response.accessTokenExpirationDate] : @"",
@"authorizeAdditionalParameters": authResponse.additionalParameters,
@"tokenAdditionalParameters": response.additionalParameters,
@"idToken": response.idToken ? response.idToken : @"",
@"refreshToken": response.refreshToken ? response.refreshToken : @"",
@"tokenType": response.tokenType ? response.tokenType : @"",
@"scopes": authResponse.scope ? [authResponse.scope componentsSeparatedByString:@" "] : [NSArray new],
};
}
- (NSDictionary*)formatRegistrationResponse: (OIDRegistrationResponse*) response {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.timeZone = [NSTimeZone timeZoneWithAbbreviation: @"UTC"];
[dateFormat setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
return @{@"clientId": response.clientID,
@"additionalParameters": response.additionalParameters,
@"clientIdIssuedAt": response.clientIDIssuedAt ? [dateFormat stringFromDate:response.clientIDIssuedAt] : @"",
@"clientSecret": response.clientSecret ? response.clientSecret : @"",
@"clientSecretExpiresAt": response.clientSecretExpiresAt ? [dateFormat stringFromDate:response.clientSecretExpiresAt] : @"",
@"registrationAccessToken": response.registrationAccessToken ? response.registrationAccessToken : @"",
@"registrationClientUri": response.registrationClientURI ? response.registrationClientURI : @"",
@"tokenEndpointAuthMethod": response.tokenEndpointAuthenticationMethod ? response.tokenEndpointAuthenticationMethod : @"",
};
}
- (NSDictionary*)formatEndSessionResponse: (OIDEndSessionResponse*)response
{
return @{@"state": response.state ? response.state : @"",
@"idTokenHint": response.request.idTokenHint,
@"postLogoutRedirectUri": response.request.postLogoutRedirectURL.absoluteString
};
}
- (NSString*)getErrorCode: (NSError*) error defaultCode: (NSString *) defaultCode {
if ([[error domain] isEqualToString:OIDOAuthAuthorizationErrorDomain]) {
switch ([error code]) {
case OIDErrorCodeOAuthAuthorizationInvalidRequest:
return @"invalid_request";
case OIDErrorCodeOAuthAuthorizationUnauthorizedClient:
return @"unauthorized_client";
case OIDErrorCodeOAuthAuthorizationAccessDenied:
return @"access_denied";
case OIDErrorCodeOAuthAuthorizationUnsupportedResponseType:
return @"unsupported_response_type";
case OIDErrorCodeOAuthAuthorizationAuthorizationInvalidScope:
return @"invalid_scope";
case OIDErrorCodeOAuthAuthorizationServerError:
return @"server_error";
case OIDErrorCodeOAuthAuthorizationTemporarilyUnavailable:
return @"temporarily_unavailable";
}
} else if ([[error domain] isEqualToString:OIDOAuthTokenErrorDomain]) {
switch ([error code]) {
case OIDErrorCodeOAuthTokenInvalidRequest:
return @"invalid_request";
case OIDErrorCodeOAuthTokenInvalidClient:
return @"invalid_client";
case OIDErrorCodeOAuthTokenInvalidGrant:
return @"invalid_grant";
case OIDErrorCodeOAuthTokenUnauthorizedClient:
return @"unauthorized_client";
case OIDErrorCodeOAuthTokenUnsupportedGrantType:
return @"unsupported_grant_type";
case OIDErrorCodeOAuthTokenInvalidScope:
return @"invalid_scope";
}
} else if ([[error domain] isEqualToString:OIDOAuthRegistrationErrorDomain]) {
switch ([error code]) {
case OIDErrorCodeOAuthRegistrationInvalidRequest:
return @"invalid_request";
case OIDErrorCodeOAuthRegistrationInvalidRedirectURI:
return @"invalid_redirect_uri";
case OIDErrorCodeOAuthRegistrationInvalidClientMetadata:
return @"invalid_client_metadata";
}
}
return defaultCode;
}
#if !TARGET_OS_MACCATALYST
- (id<OIDExternalUserAgent>)getCustomBrowser: (NSString *) browserType {
typedef id<OIDExternalUserAgent> (^BrowserBlock)(void);
NSDictionary *browsers = @{
@"safari":
^{
return [OIDExternalUserAgentIOSCustomBrowser CustomBrowserSafari];
},
@"chrome":
^{
return [OIDExternalUserAgentIOSCustomBrowser CustomBrowserChrome];
},
@"opera":
^{
return [OIDExternalUserAgentIOSCustomBrowser CustomBrowserOpera];
},
@"firefox":
^{
return [OIDExternalUserAgentIOSCustomBrowser CustomBrowserFirefox];
}
};
BrowserBlock browser = browsers[browserType];
return browser();
}
#endif
- (NSString*)getErrorMessage: (NSError*) error {
NSDictionary * userInfo = [error userInfo];
if (userInfo &&
userInfo[OIDOAuthErrorResponseErrorKey] &&
userInfo[OIDOAuthErrorResponseErrorKey][OIDOAuthErrorFieldErrorDescription]) {
return userInfo[OIDOAuthErrorResponseErrorKey][OIDOAuthErrorFieldErrorDescription];
} else {
return [error localizedDescription];
}
}
- (id<OIDExternalUserAgent>)getExternalUserAgentWithPresentingViewController: (UIViewController *)presentingViewController
prefersEphemeralSession: (BOOL *) prefersEphemeralSession
{
id<OIDExternalUserAgent> externalUserAgent;
#if TARGET_OS_MACCATALYST
externalUserAgent = [[OIDExternalUserAgentCatalyst alloc] initWithPresentingViewController:presentingViewController];
#elif TARGET_OS_IOS
if (@available(iOS 13, *)) {
externalUserAgent = [[OIDExternalUserAgentIOS alloc] initWithPresentingViewController:
presentingViewController
prefersEphemeralSession:prefersEphemeralSession];
} else {
externalUserAgent = [[OIDExternalUserAgentIOS alloc] initWithPresentingViewController:
presentingViewController];
}
#elif TARGET_OS_OSX
externalUserAgent = [[OIDExternalUserAgentMac alloc] init];
#endif
return externalUserAgent;
}
@end