FIROAuthProvider.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIROAuthProvider.h"
  17. #include <CommonCrypto/CommonCrypto.h>
  18. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRFacebookAuthProvider.h"
  19. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIROAuthCredential.h"
  20. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  21. #import "FirebaseAppCheck/Interop/FIRAppCheckTokenResultInterop.h"
  22. #import "FirebaseAuth/Sources/Auth/FIRAuthGlobalWorkQueue.h"
  23. #import "FirebaseAuth/Sources/Auth/FIRAuth_Internal.h"
  24. #import "FirebaseAuth/Sources/AuthProvider/OAuth/FIROAuthCredential_Internal.h"
  25. #import "FirebaseAuth/Sources/Backend/FIRAuthBackend.h"
  26. #import "FirebaseAuth/Sources/Backend/FIRAuthRequestConfiguration.h"
  27. #import "FirebaseAuth/Sources/Utilities/FIRAuthErrorUtils.h"
  28. #import "FirebaseAuth/Sources/Utilities/FIRAuthWebUtils.h"
  29. #if TARGET_OS_IOS
  30. #import "FirebaseAuth/Sources/Utilities/FIRAuthURLPresenter.h"
  31. #endif
  32. NS_ASSUME_NONNULL_BEGIN
  33. /** @typedef FIRHeadfulLiteURLCallBack
  34. @brief The callback invoked at the end of the flow to fetch a headful-lite URL.
  35. @param headfulLiteURL The headful lite URL.
  36. @param error The error that occurred while fetching the headful-lite, if any.
  37. */
  38. typedef void (^FIRHeadfulLiteURLCallBack)(NSURL *_Nullable headfulLiteURL,
  39. NSError *_Nullable error);
  40. /** @var kHeadfulLiteURLStringFormat
  41. @brief The format of the URL used to open the headful lite page during sign-in.
  42. */
  43. NSString *const kHeadfulLiteURLStringFormat = @"https://%@/__/auth/handler?%@";
  44. /** @var kHeadfulLiteEmulatorURLStringFormat
  45. @brief The format of the URL used to open the emulated headful lite page during sign-in.
  46. */
  47. NSString *const kHeadfulLiteEmulatorURLStringFormat = @"http://%@/emulator/auth/handler?%@";
  48. /** @var kauthTypeSignInWithRedirect
  49. @brief The auth type to be specified in the sign-in request with redirect request and response.
  50. */
  51. static NSString *const kAuthTypeSignInWithRedirect = @"signInWithRedirect";
  52. /** @var kCustomUrlSchemePrefix
  53. @brief The prefix to append to the Firebase app ID custom callback scheme..
  54. */
  55. static NSString *const kCustomUrlSchemePrefix = @"app-";
  56. @implementation FIROAuthProvider {
  57. /** @var _auth
  58. @brief The auth instance used for launching the URL presenter.
  59. */
  60. FIRAuth *_auth;
  61. /** @var _callbackScheme
  62. @brief The callback URL scheme used for headful-lite sign-in.
  63. */
  64. NSString *_callbackScheme;
  65. /** @var _usingClientIDScheme
  66. @brief True if the reverse client ID is registered as a custom URL scheme, and false
  67. otherwise.
  68. */
  69. BOOL _usingClientIDScheme;
  70. }
  71. + (FIROAuthCredential *)credentialWithProviderID:(NSString *)providerID
  72. IDToken:(NSString *)IDToken
  73. accessToken:(nullable NSString *)accessToken {
  74. return [[FIROAuthCredential alloc] initWithProviderID:providerID
  75. IDToken:IDToken
  76. rawNonce:nil
  77. accessToken:accessToken
  78. secret:nil
  79. fullName:nil
  80. pendingToken:nil];
  81. }
  82. + (FIROAuthCredential *)credentialWithProviderID:(NSString *)providerID
  83. accessToken:(NSString *)accessToken {
  84. return [[FIROAuthCredential alloc] initWithProviderID:providerID
  85. IDToken:nil
  86. rawNonce:nil
  87. accessToken:accessToken
  88. secret:nil
  89. fullName:nil
  90. pendingToken:nil];
  91. }
  92. + (FIROAuthCredential *)credentialWithProviderID:(NSString *)providerID
  93. IDToken:(NSString *)IDToken
  94. rawNonce:(nullable NSString *)rawNonce
  95. accessToken:(nullable NSString *)accessToken {
  96. return [[FIROAuthCredential alloc] initWithProviderID:providerID
  97. IDToken:IDToken
  98. rawNonce:rawNonce
  99. accessToken:accessToken
  100. secret:nil
  101. fullName:nil
  102. pendingToken:nil];
  103. }
  104. + (FIROAuthCredential *)credentialWithProviderID:(NSString *)providerID
  105. IDToken:(NSString *)IDToken
  106. rawNonce:(nullable NSString *)rawNonce {
  107. return [[FIROAuthCredential alloc] initWithProviderID:providerID
  108. IDToken:IDToken
  109. rawNonce:rawNonce
  110. accessToken:nil
  111. secret:nil
  112. fullName:nil
  113. pendingToken:nil];
  114. }
  115. + (FIROAuthCredential *)appleCredentialWithIDToken:(NSString *)IDToken
  116. rawNonce:(nullable NSString *)rawNonce
  117. fullName:(nullable NSPersonNameComponents *)fullName {
  118. return [[FIROAuthCredential alloc] initWithProviderID:@"apple.com"
  119. IDToken:IDToken
  120. rawNonce:rawNonce
  121. accessToken:nil
  122. secret:nil
  123. fullName:fullName
  124. pendingToken:nil];
  125. }
  126. + (instancetype)providerWithProviderID:(NSString *)providerID {
  127. return [[self alloc] initWithProviderID:providerID auth:[FIRAuth auth]];
  128. }
  129. + (instancetype)providerWithProviderID:(NSString *)providerID auth:(FIRAuth *)auth {
  130. return [[self alloc] initWithProviderID:providerID auth:auth];
  131. }
  132. #if TARGET_OS_IOS && (!defined(TARGET_OS_VISION) || !TARGET_OS_VISION)
  133. - (void)getCredentialWithUIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  134. completion:(nullable FIRAuthCredentialCallback)completion {
  135. if (![FIRAuthWebUtils isCallbackSchemeRegisteredForCustomURLScheme:self->_callbackScheme]) {
  136. [NSException raise:NSInternalInconsistencyException
  137. format:@"Please register custom URL scheme '%@' in the app's Info.plist file.",
  138. self->_callbackScheme];
  139. }
  140. __weak __typeof__(self) weakSelf = self;
  141. __weak FIRAuth *weakAuth = _auth;
  142. __weak NSString *weakProviderID = _providerID;
  143. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  144. FIRAuthCredentialCallback callbackOnMainThread =
  145. ^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) {
  146. if (completion) {
  147. dispatch_async(dispatch_get_main_queue(), ^{
  148. completion(credential, error);
  149. });
  150. }
  151. };
  152. NSString *eventID = [FIRAuthWebUtils randomStringWithLength:10];
  153. NSString *sessionID = [FIRAuthWebUtils randomStringWithLength:10];
  154. __strong __typeof__(self) strongSelf = weakSelf;
  155. [strongSelf
  156. getHeadFulLiteURLWithEventID:eventID
  157. sessionID:sessionID
  158. completion:^(NSURL *_Nullable headfulLiteURL, NSError *_Nullable error) {
  159. if (error) {
  160. callbackOnMainThread(nil, error);
  161. return;
  162. }
  163. FIRAuthURLCallbackMatcher callbackMatcher =
  164. ^BOOL(NSURL *_Nullable callbackURL) {
  165. return [FIRAuthWebUtils
  166. isExpectedCallbackURL:callbackURL
  167. eventID:eventID
  168. authType:kAuthTypeSignInWithRedirect
  169. callbackScheme:strongSelf->_callbackScheme];
  170. };
  171. __strong FIRAuth *strongAuth = weakAuth;
  172. [strongAuth.authURLPresenter
  173. presentURL:headfulLiteURL
  174. UIDelegate:UIDelegate
  175. callbackMatcher:callbackMatcher
  176. completion:^(NSURL *_Nullable callbackURL,
  177. NSError *_Nullable error) {
  178. if (error) {
  179. callbackOnMainThread(nil, error);
  180. return;
  181. }
  182. NSString *OAuthResponseURLString =
  183. [strongSelf OAuthResponseForURL:callbackURL
  184. error:&error];
  185. if (error) {
  186. callbackOnMainThread(nil, error);
  187. return;
  188. }
  189. __strong NSString *strongProviderID = weakProviderID;
  190. FIROAuthCredential *credential = [[FIROAuthCredential alloc]
  191. initWithProviderID:strongProviderID
  192. sessionID:sessionID
  193. OAuthResponseURLString:OAuthResponseURLString];
  194. callbackOnMainThread(credential, nil);
  195. }];
  196. }];
  197. });
  198. }
  199. #endif // TARGET_OS_IOS && (!defined(TARGET_OS_VISION) || !TARGET_OS_VISION)
  200. #pragma mark - Internal Methods
  201. /** @fn initWithProviderID:auth:
  202. @brief returns an instance of @c FIROAuthProvider associated with the provided auth instance.
  203. @param auth The Auth instance to be associated with the OAuthProvider instance.
  204. @return An Instance of @c FIROAuthProvider.
  205. */
  206. - (nullable instancetype)initWithProviderID:(NSString *)providerID auth:(FIRAuth *)auth {
  207. if (!auth.requestConfiguration.emulatorHostAndPort) {
  208. NSAssert(![providerID isEqual:FIRFacebookAuthProviderID],
  209. @"Sign in with Facebook is not supported via generic IDP; the Facebook TOS "
  210. "dictate that you must use the Facebook iOS SDK for Facebook login.");
  211. NSAssert(![providerID isEqual:@"apple.com"],
  212. @"Sign in with Apple is not supported via generic IDP; You must use the Apple iOS SDK"
  213. " for Sign in with Apple.");
  214. }
  215. self = [super init];
  216. if (self) {
  217. _auth = auth;
  218. _providerID = providerID;
  219. if (_auth.app.options.clientID) {
  220. NSString *reverseClientIDScheme =
  221. [[[_auth.app.options.clientID componentsSeparatedByString:@"."]
  222. reverseObjectEnumerator].allObjects componentsJoinedByString:@"."];
  223. if ([FIRAuthWebUtils isCallbackSchemeRegisteredForCustomURLScheme:reverseClientIDScheme]) {
  224. _callbackScheme = reverseClientIDScheme;
  225. _usingClientIDScheme = YES;
  226. }
  227. }
  228. if (!_usingClientIDScheme) {
  229. _callbackScheme = [kCustomUrlSchemePrefix
  230. stringByAppendingString:[_auth.app.options.googleAppID
  231. stringByReplacingOccurrencesOfString:@":"
  232. withString:@"-"]];
  233. }
  234. }
  235. return self;
  236. }
  237. /** @fn OAuthResponseForURL:error:
  238. @brief Parses the redirected URL and returns a string representation of the OAuth response URL.
  239. @param URL The url to be parsed for an OAuth response URL.
  240. @param error The error that occurred if any.
  241. @return The OAuth response if successful.
  242. */
  243. - (nullable NSString *)OAuthResponseForURL:(NSURL *)URL error:(NSError *_Nullable *_Nullable)error {
  244. NSDictionary<NSString *, NSString *> *URLQueryItems =
  245. [FIRAuthWebUtils dictionaryWithHttpArgumentsString:URL.query];
  246. NSURL *deepLinkURL = [NSURL URLWithString:URLQueryItems[@"deep_link_id"]];
  247. URLQueryItems = [FIRAuthWebUtils dictionaryWithHttpArgumentsString:deepLinkURL.query];
  248. NSString *queryItemLink = URLQueryItems[@"link"];
  249. if (queryItemLink) {
  250. return queryItemLink;
  251. }
  252. if (!error) {
  253. return nil;
  254. }
  255. NSData *errorData = [URLQueryItems[@"firebaseError"] dataUsingEncoding:NSUTF8StringEncoding];
  256. NSError *jsonError;
  257. NSDictionary *errorDict = [NSJSONSerialization JSONObjectWithData:errorData
  258. options:0
  259. error:&jsonError];
  260. if (jsonError) {
  261. *error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:jsonError];
  262. return nil;
  263. }
  264. *error = [FIRAuthErrorUtils URLResponseErrorWithCode:errorDict[@"code"]
  265. message:errorDict[@"message"]];
  266. if (!*error) {
  267. NSString *reason;
  268. if (errorDict[@"code"] && errorDict[@"message"]) {
  269. reason = [NSString stringWithFormat:@"[%@] - %@", errorDict[@"code"], errorDict[@"message"]];
  270. }
  271. *error = [FIRAuthErrorUtils webSignInUserInteractionFailureWithReason:reason];
  272. }
  273. return nil;
  274. }
  275. /** @fn getHeadFulLiteURLWithEventID:completion:
  276. @brief Constructs a URL used for opening a headful-lite flow using a given event
  277. ID and session ID.
  278. @param eventID The event ID used for this purpose.
  279. @param sessionID The session ID used when completing the headful lite flow.
  280. @param completion The callback invoked after the URL has been constructed or an error
  281. has been encountered.
  282. */
  283. - (void)getHeadFulLiteURLWithEventID:(NSString *)eventID
  284. sessionID:(NSString *)sessionID
  285. completion:(FIRHeadfulLiteURLCallBack)completion {
  286. __weak __typeof__(self) weakSelf = self;
  287. [FIRAuthWebUtils
  288. fetchAuthDomainWithRequestConfiguration:_auth.requestConfiguration
  289. completion:^(NSString *_Nullable authDomain,
  290. NSError *_Nullable error) {
  291. if (error) {
  292. if (completion) {
  293. completion(nil, error);
  294. }
  295. return;
  296. }
  297. __strong __typeof__(self) strongSelf = weakSelf;
  298. NSString *bundleID = [NSBundle mainBundle].bundleIdentifier;
  299. NSString *clientID = strongSelf->_auth.app.options.clientID;
  300. NSString *appID = strongSelf->_auth.app.options.googleAppID;
  301. NSString *apiKey =
  302. strongSelf->_auth.requestConfiguration.APIKey;
  303. NSString *tenantID = strongSelf->_auth.tenantID;
  304. id<FIRAppCheckInterop> appCheck =
  305. strongSelf->_auth.requestConfiguration.appCheck;
  306. NSMutableDictionary *urlArguments = [@{
  307. @"apiKey" : apiKey,
  308. @"authType" : kAuthTypeSignInWithRedirect,
  309. @"ibi" : bundleID ?: @"",
  310. @"sessionId" : [strongSelf hashforString:sessionID],
  311. @"v" : [FIRAuthBackend authUserAgent],
  312. @"eventId" : eventID,
  313. @"providerId" : strongSelf->_providerID,
  314. } mutableCopy];
  315. if (strongSelf->_usingClientIDScheme) {
  316. urlArguments[@"clientId"] = clientID;
  317. } else {
  318. urlArguments[@"appId"] = appID;
  319. }
  320. if (tenantID) {
  321. urlArguments[@"tid"] = tenantID;
  322. }
  323. if (strongSelf.scopes.count) {
  324. urlArguments[@"scopes"] =
  325. [strongSelf.scopes componentsJoinedByString:@","];
  326. }
  327. if (strongSelf.customParameters.count) {
  328. NSString *customParameters =
  329. [strongSelf customParametersStringWithError:&error];
  330. if (error) {
  331. completion(nil, error);
  332. return;
  333. }
  334. if (customParameters) {
  335. urlArguments[@"customParameters"] = customParameters;
  336. }
  337. }
  338. if (strongSelf->_auth.requestConfiguration.languageCode) {
  339. urlArguments[@"hl"] =
  340. strongSelf->_auth.requestConfiguration.languageCode;
  341. }
  342. NSString *argumentsString = [strongSelf
  343. httpArgumentsStringForArgsDictionary:urlArguments];
  344. NSString *URLString;
  345. if (strongSelf->_auth.requestConfiguration
  346. .emulatorHostAndPort) {
  347. URLString = [NSString
  348. stringWithFormat:kHeadfulLiteEmulatorURLStringFormat,
  349. authDomain, argumentsString];
  350. } else {
  351. URLString =
  352. [NSString stringWithFormat:kHeadfulLiteURLStringFormat,
  353. authDomain, argumentsString];
  354. }
  355. NSCharacterSet *set =
  356. [NSCharacterSet URLFragmentAllowedCharacterSet];
  357. NSURLComponents *components = [[NSURLComponents alloc]
  358. initWithString:
  359. [URLString
  360. stringByAddingPercentEncodingWithAllowedCharacters:
  361. set]];
  362. if (appCheck) {
  363. [appCheck
  364. getTokenForcingRefresh:false
  365. completion:^(
  366. id<FIRAppCheckTokenResultInterop> _Nonnull tokenResult) {
  367. if (tokenResult.error) {
  368. FIRLogWarning(
  369. kFIRLoggerAuth, @"I-AUT000018",
  370. @"Error getting App Check token; "
  371. @"using placeholder token "
  372. @"instead. Error: %@",
  373. tokenResult.error);
  374. }
  375. NSString *appCheckTokenFragment = [@"fac="
  376. stringByAppendingString:tokenResult
  377. .token];
  378. [components
  379. setFragment:appCheckTokenFragment];
  380. if (completion) {
  381. completion([components URL], nil);
  382. }
  383. }];
  384. } else {
  385. if (completion) {
  386. completion([components URL], nil);
  387. }
  388. }
  389. }];
  390. }
  391. /** @fn customParametersString
  392. @brief Returns a JSON string representation of the custom parameters dictionary corresponding
  393. to the OAuthProvider.
  394. @return The JSON string representation of the custom parameters dictionary corresponding
  395. to the OAuthProvider.
  396. */
  397. - (nullable NSString *)customParametersStringWithError:(NSError *_Nullable *_Nullable)error {
  398. if (!_customParameters.count) {
  399. return nil;
  400. }
  401. if (!error) {
  402. return nil;
  403. }
  404. NSError *jsonError;
  405. NSData *customParametersJSONData = [NSJSONSerialization dataWithJSONObject:_customParameters
  406. options:0
  407. error:&jsonError];
  408. if (jsonError) {
  409. *error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:jsonError];
  410. return nil;
  411. }
  412. NSString *customParamsRawJSON = [[NSString alloc] initWithData:customParametersJSONData
  413. encoding:NSUTF8StringEncoding];
  414. return customParamsRawJSON;
  415. }
  416. /** @fn hashforString:
  417. @brief Returns the SHA256 hash representation of a given string object.
  418. @param string The string for which a SHA256 hash is desired.
  419. @return An hexadecimal string representation of the SHA256 hash.
  420. */
  421. - (NSString *)hashforString:(NSString *)string {
  422. NSData *sessionIDData = [string dataUsingEncoding:NSUTF8StringEncoding];
  423. NSMutableData *hashOutputData = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
  424. if (CC_SHA256(sessionIDData.bytes, (CC_LONG)[sessionIDData length],
  425. hashOutputData.mutableBytes)) {
  426. }
  427. return [self hexStringFromData:hashOutputData];
  428. ;
  429. }
  430. /** @fn hexStringFromData:
  431. @brief Returns the hexadecimal string representation of an NSData object.
  432. @param data The NSData object for which a hexadecical string is desired.
  433. @return The hexadecimal string representation of the supplied NSData object.
  434. */
  435. - (NSString *)hexStringFromData:(NSData *)data {
  436. const unsigned char *dataBuffer = (const unsigned char *)[data bytes];
  437. NSMutableString *string = [[NSMutableString alloc] init];
  438. for (unsigned int i = 0; i < data.length; i++) {
  439. [string appendFormat:@"%02lx", (unsigned long)dataBuffer[i]];
  440. }
  441. return [string copy];
  442. }
  443. - (NSString *)httpArgumentsStringForArgsDictionary:(NSDictionary *)argsDictionary {
  444. NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:argsDictionary.count];
  445. NSString *key;
  446. for (key in argsDictionary) {
  447. NSString *description = [argsDictionary[key] description];
  448. [arguments
  449. addObject:[NSString
  450. stringWithFormat:@"%@=%@",
  451. [FIRAuthWebUtils stringByUnescapingFromURLArgument:key],
  452. [FIRAuthWebUtils
  453. stringByUnescapingFromURLArgument:description]]];
  454. }
  455. return [arguments componentsJoinedByString:@"&"];
  456. }
  457. @end
  458. NS_ASSUME_NONNULL_END