No Description

FIROAuthProvider.m 16KB

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