FIROAuthProvider.m 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. if (!auth.requestConfiguration.emulatorHostAndPort) {
  187. NSAssert(![providerID isEqual:FIRFacebookAuthProviderID],
  188. @"Sign in with Facebook is not supported via generic IDP; the Facebook TOS "
  189. "dictate that you must use the Facebook iOS SDK for Facebook login.");
  190. NSAssert(![providerID isEqual:@"apple.com"],
  191. @"Sign in with Apple is not supported via generic IDP; You must use the Apple iOS SDK"
  192. " for Sign in with Apple.");
  193. }
  194. self = [super init];
  195. if (self) {
  196. _auth = auth;
  197. _providerID = providerID;
  198. if (_auth.app.options.clientID) {
  199. _callbackScheme = [[[_auth.app.options.clientID componentsSeparatedByString:@"."]
  200. reverseObjectEnumerator].allObjects componentsJoinedByString:@"."];
  201. } else {
  202. _callbackScheme = [kCustomUrlSchemePrefix
  203. stringByAppendingString:[_auth.app.options.googleAppID
  204. stringByReplacingOccurrencesOfString:@":"
  205. withString:@"-"]];
  206. }
  207. }
  208. return self;
  209. }
  210. /** @fn OAuthResponseForURL:error:
  211. @brief Parses the redirected URL and returns a string representation of the OAuth response URL.
  212. @param URL The url to be parsed for an OAuth response URL.
  213. @param error The error that occurred if any.
  214. @return The OAuth response if successful.
  215. */
  216. - (nullable NSString *)OAuthResponseForURL:(NSURL *)URL error:(NSError *_Nullable *_Nullable)error {
  217. NSDictionary<NSString *, NSString *> *URLQueryItems =
  218. [FIRAuthWebUtils dictionaryWithHttpArgumentsString:URL.query];
  219. NSURL *deepLinkURL = [NSURL URLWithString:URLQueryItems[@"deep_link_id"]];
  220. URLQueryItems = [FIRAuthWebUtils dictionaryWithHttpArgumentsString:deepLinkURL.query];
  221. NSString *queryItemLink = URLQueryItems[@"link"];
  222. if (queryItemLink) {
  223. return queryItemLink;
  224. }
  225. if (!error) {
  226. return nil;
  227. }
  228. NSData *errorData = [URLQueryItems[@"firebaseError"] dataUsingEncoding:NSUTF8StringEncoding];
  229. NSError *jsonError;
  230. NSDictionary *errorDict = [NSJSONSerialization JSONObjectWithData:errorData
  231. options:0
  232. error:&jsonError];
  233. if (jsonError) {
  234. *error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:jsonError];
  235. return nil;
  236. }
  237. *error = [FIRAuthErrorUtils URLResponseErrorWithCode:errorDict[@"code"]
  238. message:errorDict[@"message"]];
  239. if (!*error) {
  240. NSString *reason;
  241. if (errorDict[@"code"] && errorDict[@"message"]) {
  242. reason = [NSString stringWithFormat:@"[%@] - %@", errorDict[@"code"], errorDict[@"message"]];
  243. }
  244. *error = [FIRAuthErrorUtils webSignInUserInteractionFailureWithReason:reason];
  245. }
  246. return nil;
  247. }
  248. /** @fn getHeadFulLiteURLWithEventID:completion:
  249. @brief Constructs a URL used for opening a headful-lite flow using a given event
  250. ID and session ID.
  251. @param eventID The event ID used for this purpose.
  252. @param sessionID The session ID used when completing the headful lite flow.
  253. @param completion The callback invoked after the URL has been constructed or an error
  254. has been encountered.
  255. */
  256. - (void)getHeadFulLiteURLWithEventID:(NSString *)eventID
  257. sessionID:(NSString *)sessionID
  258. completion:(FIRHeadfulLiteURLCallBack)completion {
  259. __weak __typeof__(self) weakSelf = self;
  260. [FIRAuthWebUtils
  261. fetchAuthDomainWithRequestConfiguration:_auth.requestConfiguration
  262. completion:^(NSString *_Nullable authDomain,
  263. NSError *_Nullable error) {
  264. if (error) {
  265. if (completion) {
  266. completion(nil, error);
  267. }
  268. return;
  269. }
  270. __strong __typeof__(self) strongSelf = weakSelf;
  271. NSString *bundleID = [NSBundle mainBundle].bundleIdentifier;
  272. NSString *clientID = strongSelf->_auth.app.options.clientID;
  273. NSString *appID = strongSelf->_auth.app.options.googleAppID;
  274. NSString *apiKey =
  275. strongSelf->_auth.requestConfiguration.APIKey;
  276. NSMutableDictionary *urlArguments = [@{
  277. @"apiKey" : apiKey,
  278. @"authType" : kAuthTypeSignInWithRedirect,
  279. @"ibi" : bundleID ?: @"",
  280. @"sessionId" : [strongSelf hashforString:sessionID],
  281. @"v" : [FIRAuthBackend authUserAgent],
  282. @"eventId" : eventID,
  283. @"providerId" : strongSelf->_providerID,
  284. } mutableCopy];
  285. if (clientID) {
  286. urlArguments[@"clientId"] = clientID;
  287. } else {
  288. urlArguments[@"appId"] = appID;
  289. }
  290. if (strongSelf.scopes.count) {
  291. urlArguments[@"scopes"] =
  292. [strongSelf.scopes componentsJoinedByString:@","];
  293. }
  294. if (strongSelf.customParameters.count) {
  295. NSString *customParameters =
  296. [strongSelf customParametersStringWithError:&error];
  297. if (error) {
  298. completion(nil, error);
  299. return;
  300. }
  301. if (customParameters) {
  302. urlArguments[@"customParameters"] = customParameters;
  303. }
  304. }
  305. if (strongSelf->_auth.requestConfiguration.languageCode) {
  306. urlArguments[@"hl"] =
  307. strongSelf->_auth.requestConfiguration.languageCode;
  308. }
  309. NSString *argumentsString = [strongSelf
  310. httpArgumentsStringForArgsDictionary:urlArguments];
  311. NSString *URLString;
  312. if (strongSelf->_auth.requestConfiguration
  313. .emulatorHostAndPort) {
  314. URLString = [NSString
  315. stringWithFormat:kHeadfulLiteEmulatorURLStringFormat,
  316. authDomain, argumentsString];
  317. } else {
  318. URLString =
  319. [NSString stringWithFormat:kHeadfulLiteURLStringFormat,
  320. authDomain, argumentsString];
  321. }
  322. if (completion) {
  323. NSCharacterSet *set =
  324. [NSCharacterSet URLFragmentAllowedCharacterSet];
  325. completion(
  326. [NSURL
  327. URLWithString:
  328. [URLString
  329. stringByAddingPercentEncodingWithAllowedCharacters:
  330. set]],
  331. nil);
  332. }
  333. }];
  334. }
  335. /** @fn customParametersString
  336. @brief Returns a JSON string representation of the custom parameters dictionary corresponding
  337. to the OAuthProvider.
  338. @return The JSON string representation of the custom parameters dictionary corresponding
  339. to the OAuthProvider.
  340. */
  341. - (nullable NSString *)customParametersStringWithError:(NSError *_Nullable *_Nullable)error {
  342. if (!_customParameters.count) {
  343. return nil;
  344. }
  345. if (!error) {
  346. return nil;
  347. }
  348. NSError *jsonError;
  349. NSData *customParametersJSONData = [NSJSONSerialization dataWithJSONObject:_customParameters
  350. options:0
  351. error:&jsonError];
  352. if (jsonError) {
  353. *error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:jsonError];
  354. return nil;
  355. }
  356. NSString *customParamsRawJSON = [[NSString alloc] initWithData:customParametersJSONData
  357. encoding:NSUTF8StringEncoding];
  358. return customParamsRawJSON;
  359. }
  360. /** @fn hashforString:
  361. @brief Returns the SHA256 hash representation of a given string object.
  362. @param string The string for which a SHA256 hash is desired.
  363. @return An hexadecimal string representation of the SHA256 hash.
  364. */
  365. - (NSString *)hashforString:(NSString *)string {
  366. NSData *sessionIDData = [string dataUsingEncoding:NSUTF8StringEncoding];
  367. NSMutableData *hashOutputData = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
  368. if (CC_SHA256(sessionIDData.bytes, (CC_LONG)[sessionIDData length],
  369. hashOutputData.mutableBytes)) {
  370. }
  371. return [self hexStringFromData:hashOutputData];
  372. ;
  373. }
  374. /** @fn hexStringFromData:
  375. @brief Returns the hexadecimal string representation of an NSData object.
  376. @param data The NSData object for which a hexadecical string is desired.
  377. @return The hexadecimal string representation of the supplied NSData object.
  378. */
  379. - (NSString *)hexStringFromData:(NSData *)data {
  380. const unsigned char *dataBuffer = (const unsigned char *)[data bytes];
  381. NSMutableString *string = [[NSMutableString alloc] init];
  382. for (unsigned int i = 0; i < data.length; i++) {
  383. [string appendFormat:@"%02lx", (unsigned long)dataBuffer[i]];
  384. }
  385. return [string copy];
  386. }
  387. - (NSString *)httpArgumentsStringForArgsDictionary:(NSDictionary *)argsDictionary {
  388. NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:argsDictionary.count];
  389. NSString *key;
  390. for (key in argsDictionary) {
  391. NSString *description = [argsDictionary[key] description];
  392. [arguments
  393. addObject:[NSString
  394. stringWithFormat:@"%@=%@",
  395. [FIRAuthWebUtils stringByUnescapingFromURLArgument:key],
  396. [FIRAuthWebUtils
  397. stringByUnescapingFromURLArgument:description]]];
  398. }
  399. return [arguments componentsJoinedByString:@"&"];
  400. }
  401. @end
  402. NS_ASSUME_NONNULL_END