FIROAuthProvider.m 14 KB

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