FIROAuthProvider.m 21 KB

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