FIROAuthProvider.m 20 KB

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