FIROAuthProvider.m 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 "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_async(FIRAuthGlobalWorkQueue(), ^{
  128. FIRAuthCredentialCallback callbackOnMainThread =
  129. ^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) {
  130. if (completion) {
  131. dispatch_async(dispatch_get_main_queue(), ^{
  132. completion(credential, error);
  133. });
  134. }
  135. };
  136. NSString *eventID = [FIRAuthWebUtils randomStringWithLength:10];
  137. NSString *sessionID = [FIRAuthWebUtils randomStringWithLength:10];
  138. __strong __typeof__(self) strongSelf = weakSelf;
  139. [strongSelf
  140. getHeadFulLiteURLWithEventID:eventID
  141. sessionID:sessionID
  142. completion:^(NSURL *_Nullable headfulLiteURL, NSError *_Nullable error) {
  143. if (error) {
  144. callbackOnMainThread(nil, error);
  145. return;
  146. }
  147. FIRAuthURLCallbackMatcher callbackMatcher =
  148. ^BOOL(NSURL *_Nullable callbackURL) {
  149. return [FIRAuthWebUtils
  150. isExpectedCallbackURL:callbackURL
  151. eventID:eventID
  152. authType:kAuthTypeSignInWithRedirect
  153. callbackScheme:strongSelf->_callbackScheme];
  154. };
  155. __strong FIRAuth *strongAuth = weakAuth;
  156. [strongAuth.authURLPresenter
  157. presentURL:headfulLiteURL
  158. UIDelegate:UIDelegate
  159. callbackMatcher:callbackMatcher
  160. completion:^(NSURL *_Nullable callbackURL,
  161. NSError *_Nullable error) {
  162. if (error) {
  163. callbackOnMainThread(nil, error);
  164. return;
  165. }
  166. NSString *OAuthResponseURLString =
  167. [strongSelf OAuthResponseForURL:callbackURL
  168. error:&error];
  169. if (error) {
  170. callbackOnMainThread(nil, error);
  171. return;
  172. }
  173. __strong NSString *strongProviderID = weakProviderID;
  174. FIROAuthCredential *credential = [[FIROAuthCredential alloc]
  175. initWithProviderID:strongProviderID
  176. sessionID:sessionID
  177. OAuthResponseURLString:OAuthResponseURLString];
  178. callbackOnMainThread(credential, nil);
  179. }];
  180. }];
  181. });
  182. }
  183. #endif // TARGET_OS_IOS
  184. #pragma mark - Internal Methods
  185. /** @fn initWithProviderID:auth:
  186. @brief returns an instance of @c FIROAuthProvider associated with the provided auth instance.
  187. @param auth The Auth instance to be associated with the OAuthProvider instance.
  188. @return An Instance of @c FIROAuthProvider.
  189. */
  190. - (nullable instancetype)initWithProviderID:(NSString *)providerID auth:(FIRAuth *)auth {
  191. if (!auth.requestConfiguration.emulatorHostAndPort) {
  192. NSAssert(![providerID isEqual:FIRFacebookAuthProviderID],
  193. @"Sign in with Facebook is not supported via generic IDP; the Facebook TOS "
  194. "dictate that you must use the Facebook iOS SDK for Facebook login.");
  195. NSAssert(![providerID isEqual:@"apple.com"],
  196. @"Sign in with Apple is not supported via generic IDP; You must use the Apple iOS SDK"
  197. " for Sign in with Apple.");
  198. }
  199. self = [super init];
  200. if (self) {
  201. _auth = auth;
  202. _providerID = providerID;
  203. if (_auth.app.options.clientID) {
  204. NSString *reverseClientIDScheme =
  205. [[[_auth.app.options.clientID componentsSeparatedByString:@"."]
  206. reverseObjectEnumerator].allObjects componentsJoinedByString:@"."];
  207. if ([FIRAuthWebUtils isCallbackSchemeRegisteredForCustomURLScheme:reverseClientIDScheme]) {
  208. _callbackScheme = reverseClientIDScheme;
  209. _usingClientIDScheme = YES;
  210. }
  211. }
  212. if (!_usingClientIDScheme) {
  213. _callbackScheme = [kCustomUrlSchemePrefix
  214. stringByAppendingString:[_auth.app.options.googleAppID
  215. stringByReplacingOccurrencesOfString:@":"
  216. withString:@"-"]];
  217. }
  218. }
  219. return self;
  220. }
  221. /** @fn OAuthResponseForURL:error:
  222. @brief Parses the redirected URL and returns a string representation of the OAuth response URL.
  223. @param URL The url to be parsed for an OAuth response URL.
  224. @param error The error that occurred if any.
  225. @return The OAuth response if successful.
  226. */
  227. - (nullable NSString *)OAuthResponseForURL:(NSURL *)URL error:(NSError *_Nullable *_Nullable)error {
  228. NSDictionary<NSString *, NSString *> *URLQueryItems =
  229. [FIRAuthWebUtils dictionaryWithHttpArgumentsString:URL.query];
  230. NSURL *deepLinkURL = [NSURL URLWithString:URLQueryItems[@"deep_link_id"]];
  231. URLQueryItems = [FIRAuthWebUtils dictionaryWithHttpArgumentsString:deepLinkURL.query];
  232. NSString *queryItemLink = URLQueryItems[@"link"];
  233. if (queryItemLink) {
  234. return queryItemLink;
  235. }
  236. if (!error) {
  237. return nil;
  238. }
  239. NSData *errorData = [URLQueryItems[@"firebaseError"] dataUsingEncoding:NSUTF8StringEncoding];
  240. NSError *jsonError;
  241. NSDictionary *errorDict = [NSJSONSerialization JSONObjectWithData:errorData
  242. options:0
  243. error:&jsonError];
  244. if (jsonError) {
  245. *error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:jsonError];
  246. return nil;
  247. }
  248. *error = [FIRAuthErrorUtils URLResponseErrorWithCode:errorDict[@"code"]
  249. message:errorDict[@"message"]];
  250. if (!*error) {
  251. NSString *reason;
  252. if (errorDict[@"code"] && errorDict[@"message"]) {
  253. reason = [NSString stringWithFormat:@"[%@] - %@", errorDict[@"code"], errorDict[@"message"]];
  254. }
  255. *error = [FIRAuthErrorUtils webSignInUserInteractionFailureWithReason:reason];
  256. }
  257. return nil;
  258. }
  259. /** @fn getHeadFulLiteURLWithEventID:completion:
  260. @brief Constructs a URL used for opening a headful-lite flow using a given event
  261. ID and session ID.
  262. @param eventID The event ID used for this purpose.
  263. @param sessionID The session ID used when completing the headful lite flow.
  264. @param completion The callback invoked after the URL has been constructed or an error
  265. has been encountered.
  266. */
  267. - (void)getHeadFulLiteURLWithEventID:(NSString *)eventID
  268. sessionID:(NSString *)sessionID
  269. completion:(FIRHeadfulLiteURLCallBack)completion {
  270. __weak __typeof__(self) weakSelf = self;
  271. [FIRAuthWebUtils
  272. fetchAuthDomainWithRequestConfiguration:_auth.requestConfiguration
  273. completion:^(NSString *_Nullable authDomain,
  274. NSError *_Nullable error) {
  275. if (error) {
  276. if (completion) {
  277. completion(nil, error);
  278. }
  279. return;
  280. }
  281. __strong __typeof__(self) strongSelf = weakSelf;
  282. NSString *bundleID = [NSBundle mainBundle].bundleIdentifier;
  283. NSString *clientID = strongSelf->_auth.app.options.clientID;
  284. NSString *appID = strongSelf->_auth.app.options.googleAppID;
  285. NSString *apiKey =
  286. strongSelf->_auth.requestConfiguration.APIKey;
  287. NSString *tenantID = strongSelf->_auth.tenantID;
  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 (tenantID) {
  303. urlArguments[@"tid"] = tenantID;
  304. }
  305. if (strongSelf.scopes.count) {
  306. urlArguments[@"scopes"] =
  307. [strongSelf.scopes componentsJoinedByString:@","];
  308. }
  309. if (strongSelf.customParameters.count) {
  310. NSString *customParameters =
  311. [strongSelf customParametersStringWithError:&error];
  312. if (error) {
  313. completion(nil, error);
  314. return;
  315. }
  316. if (customParameters) {
  317. urlArguments[@"customParameters"] = customParameters;
  318. }
  319. }
  320. if (strongSelf->_auth.requestConfiguration.languageCode) {
  321. urlArguments[@"hl"] =
  322. strongSelf->_auth.requestConfiguration.languageCode;
  323. }
  324. NSString *argumentsString = [strongSelf
  325. httpArgumentsStringForArgsDictionary:urlArguments];
  326. NSString *URLString;
  327. if (strongSelf->_auth.requestConfiguration
  328. .emulatorHostAndPort) {
  329. URLString = [NSString
  330. stringWithFormat:kHeadfulLiteEmulatorURLStringFormat,
  331. authDomain, argumentsString];
  332. } else {
  333. URLString =
  334. [NSString stringWithFormat:kHeadfulLiteURLStringFormat,
  335. authDomain, argumentsString];
  336. }
  337. if (completion) {
  338. NSCharacterSet *set =
  339. [NSCharacterSet URLFragmentAllowedCharacterSet];
  340. completion(
  341. [NSURL
  342. URLWithString:
  343. [URLString
  344. stringByAddingPercentEncodingWithAllowedCharacters:
  345. set]],
  346. nil);
  347. }
  348. }];
  349. }
  350. /** @fn customParametersString
  351. @brief Returns a JSON string representation of the custom parameters dictionary corresponding
  352. to the OAuthProvider.
  353. @return The JSON string representation of the custom parameters dictionary corresponding
  354. to the OAuthProvider.
  355. */
  356. - (nullable NSString *)customParametersStringWithError:(NSError *_Nullable *_Nullable)error {
  357. if (!_customParameters.count) {
  358. return nil;
  359. }
  360. if (!error) {
  361. return nil;
  362. }
  363. NSError *jsonError;
  364. NSData *customParametersJSONData = [NSJSONSerialization dataWithJSONObject:_customParameters
  365. options:0
  366. error:&jsonError];
  367. if (jsonError) {
  368. *error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:jsonError];
  369. return nil;
  370. }
  371. NSString *customParamsRawJSON = [[NSString alloc] initWithData:customParametersJSONData
  372. encoding:NSUTF8StringEncoding];
  373. return customParamsRawJSON;
  374. }
  375. /** @fn hashforString:
  376. @brief Returns the SHA256 hash representation of a given string object.
  377. @param string The string for which a SHA256 hash is desired.
  378. @return An hexadecimal string representation of the SHA256 hash.
  379. */
  380. - (NSString *)hashforString:(NSString *)string {
  381. NSData *sessionIDData = [string dataUsingEncoding:NSUTF8StringEncoding];
  382. NSMutableData *hashOutputData = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
  383. if (CC_SHA256(sessionIDData.bytes, (CC_LONG)[sessionIDData length],
  384. hashOutputData.mutableBytes)) {
  385. }
  386. return [self hexStringFromData:hashOutputData];
  387. ;
  388. }
  389. /** @fn hexStringFromData:
  390. @brief Returns the hexadecimal string representation of an NSData object.
  391. @param data The NSData object for which a hexadecical string is desired.
  392. @return The hexadecimal string representation of the supplied NSData object.
  393. */
  394. - (NSString *)hexStringFromData:(NSData *)data {
  395. const unsigned char *dataBuffer = (const unsigned char *)[data bytes];
  396. NSMutableString *string = [[NSMutableString alloc] init];
  397. for (unsigned int i = 0; i < data.length; i++) {
  398. [string appendFormat:@"%02lx", (unsigned long)dataBuffer[i]];
  399. }
  400. return [string copy];
  401. }
  402. - (NSString *)httpArgumentsStringForArgsDictionary:(NSDictionary *)argsDictionary {
  403. NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:argsDictionary.count];
  404. NSString *key;
  405. for (key in argsDictionary) {
  406. NSString *description = [argsDictionary[key] description];
  407. [arguments
  408. addObject:[NSString
  409. stringWithFormat:@"%@=%@",
  410. [FIRAuthWebUtils stringByUnescapingFromURLArgument:key],
  411. [FIRAuthWebUtils
  412. stringByUnescapingFromURLArgument:description]]];
  413. }
  414. return [arguments componentsJoinedByString:@"&"];
  415. }
  416. @end
  417. NS_ASSUME_NONNULL_END