FIROAuthProvider.m 21 KB

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