GIDSignIn.m 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDSignIn.h"
  15. #import "GoogleSignIn/Sources/GIDSignIn_Private.h"
  16. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDConfiguration.h"
  17. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDGoogleUser.h"
  18. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDProfileData.h"
  19. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDSignInResult.h"
  20. #import "GoogleSignIn/Sources/GIDEMMSupport.h"
  21. #import "GoogleSignIn/Sources/GIDSignInInternalOptions.h"
  22. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  23. #import "GoogleSignIn/Sources/GIDCallbackQueue.h"
  24. #import "GoogleSignIn/Sources/GIDScopes.h"
  25. #import "GoogleSignIn/Sources/GIDSignInCallbackSchemes.h"
  26. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  27. #import "GoogleSignIn/Sources/GIDAuthStateMigration.h"
  28. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  29. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  30. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  31. #import "GoogleSignIn/Sources/GIDProfileData_Private.h"
  32. #import "GoogleSignIn/Sources/GIDSignInResult_Private.h"
  33. #ifdef SWIFT_PACKAGE
  34. @import AppAuth;
  35. @import GTMAppAuth;
  36. @import GTMSessionFetcherCore;
  37. #else
  38. #import <AppAuth/OIDAuthState.h>
  39. #import <AppAuth/OIDAuthorizationRequest.h>
  40. #import <AppAuth/OIDAuthorizationResponse.h>
  41. #import <AppAuth/OIDAuthorizationService.h>
  42. #import <AppAuth/OIDError.h>
  43. #import <AppAuth/OIDExternalUserAgentSession.h>
  44. #import <AppAuth/OIDIDToken.h>
  45. #import <AppAuth/OIDResponseTypes.h>
  46. #import <AppAuth/OIDServiceConfiguration.h>
  47. #import <AppAuth/OIDTokenRequest.h>
  48. #import <AppAuth/OIDTokenResponse.h>
  49. #import <AppAuth/OIDURLQueryComponent.h>
  50. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization+Keychain.h>
  51. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization.h>
  52. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  53. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  54. #import <AppAuth/OIDAuthorizationService+IOS.h>
  55. #elif TARGET_OS_OSX
  56. #import <AppAuth/OIDAuthorizationService+Mac.h>
  57. #endif
  58. #endif
  59. NS_ASSUME_NONNULL_BEGIN
  60. // The name of the query parameter used for logging the restart of auth from EMM callback.
  61. static NSString *const kEMMRestartAuthParameter = @"emmres";
  62. // The URL template for the authorization endpoint.
  63. static NSString *const kAuthorizationURLTemplate = @"https://%@/o/oauth2/v2/auth";
  64. // The URL template for the token endpoint.
  65. static NSString *const kTokenURLTemplate = @"https://%@/token";
  66. // The URL template for the URL to get user info.
  67. static NSString *const kUserInfoURLTemplate = @"https://%@/oauth2/v3/userinfo?access_token=%@";
  68. // The URL template for the URL to revoke the token.
  69. static NSString *const kRevokeTokenURLTemplate = @"https://%@/o/oauth2/revoke?token=%@";
  70. // Expected path in the URL scheme to be handled.
  71. static NSString *const kBrowserCallbackPath = @"/oauth2callback";
  72. // Expected path for EMM callback.
  73. static NSString *const kEMMCallbackPath = @"/emmcallback";
  74. // The EMM support version
  75. static NSString *const kEMMVersion = @"1";
  76. // The error code for Google Identity.
  77. NSErrorDomain const kGIDSignInErrorDomain = @"com.google.GIDSignIn";
  78. // Keychain constants for saving state in the authentication flow.
  79. static NSString *const kGTMAppAuthKeychainName = @"auth";
  80. // Basic profile (Fat ID Token / userinfo endpoint) keys
  81. static NSString *const kBasicProfileEmailKey = @"email";
  82. static NSString *const kBasicProfilePictureKey = @"picture";
  83. static NSString *const kBasicProfileNameKey = @"name";
  84. static NSString *const kBasicProfileGivenNameKey = @"given_name";
  85. static NSString *const kBasicProfileFamilyNameKey = @"family_name";
  86. // Parameters in the callback URL coming back from browser.
  87. static NSString *const kAuthorizationCodeKeyName = @"code";
  88. static NSString *const kOAuth2ErrorKeyName = @"error";
  89. static NSString *const kOAuth2AccessDenied = @"access_denied";
  90. static NSString *const kEMMPasscodeInfoRequiredKeyName = @"emm_passcode_info_required";
  91. // Error string for unavailable keychain.
  92. static NSString *const kKeychainError = @"keychain error";
  93. // Error string for user cancelations.
  94. static NSString *const kUserCanceledError = @"The user canceled the sign-in flow.";
  95. // User preference key to detect fresh install of the app.
  96. static NSString *const kAppHasRunBeforeKey = @"GID_AppHasRunBefore";
  97. // Maximum retry interval in seconds for the fetcher.
  98. static const NSTimeInterval kFetcherMaxRetryInterval = 15.0;
  99. // The delay before the new sign-in flow can be presented after the existing one is cancelled.
  100. static const NSTimeInterval kPresentationDelayAfterCancel = 1.0;
  101. // Parameters for the auth and token exchange endpoints.
  102. static NSString *const kAudienceParameter = @"audience";
  103. // See b/11669751 .
  104. static NSString *const kOpenIDRealmParameter = @"openid.realm";
  105. static NSString *const kIncludeGrantedScopesParameter = @"include_granted_scopes";
  106. static NSString *const kLoginHintParameter = @"login_hint";
  107. static NSString *const kHostedDomainParameter = @"hd";
  108. // Minimum time to expiration for a restored access token.
  109. static const NSTimeInterval kMinimumRestoredAccessTokenTimeToExpire = 600.0;
  110. // Info.plist config keys
  111. static NSString *const kConfigClientIDKey = @"GIDClientID";
  112. static NSString *const kConfigServerClientIDKey = @"GIDServerClientID";
  113. static NSString *const kConfigHostedDomainKey = @"GIDHostedDomain";
  114. static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
  115. // The callback queue used for authentication flow.
  116. @interface GIDAuthFlow : GIDCallbackQueue
  117. @property(nonatomic, strong, nullable) OIDAuthState *authState;
  118. @property(nonatomic, strong, nullable) NSError *error;
  119. @property(nonatomic, copy, nullable) NSString *emmSupport;
  120. @property(nonatomic, nullable) GIDProfileData *profileData;
  121. @end
  122. @implementation GIDAuthFlow
  123. @end
  124. @implementation GIDSignIn {
  125. // This value is used when sign-in flows are resumed via the handling of a URL. Its value is
  126. // set when a sign-in flow is begun via |signInWithOptions:| when the options passed don't
  127. // represent a sign in continuation.
  128. GIDSignInInternalOptions *_currentOptions;
  129. // AppAuth configuration object.
  130. OIDServiceConfiguration *_appAuthConfiguration;
  131. // AppAuth external user-agent session state.
  132. id<OIDExternalUserAgentSession> _currentAuthorizationFlow;
  133. // Flag to indicate that the auth flow is restarting.
  134. BOOL _restarting;
  135. }
  136. #pragma mark - Public methods
  137. // Handles the custom scheme URL opened by SFSafariViewController or the Device Policy App.
  138. //
  139. // For SFSafariViewController invoked via AppAuth, this method is used on iOS 10.
  140. // For the Device Policy App (EMM flow) this method is used on all iOS versions.
  141. - (BOOL)handleURL:(NSURL *)url {
  142. // Check if the callback path matches the expected one for a URL from Safari/Chrome/SafariVC.
  143. if ([url.path isEqual:kBrowserCallbackPath]) {
  144. if ([_currentAuthorizationFlow resumeExternalUserAgentFlowWithURL:url]) {
  145. _currentAuthorizationFlow = nil;
  146. return YES;
  147. }
  148. return NO;
  149. }
  150. // Check if the callback path matches the expected one for a URL from Google Device Policy app.
  151. if ([url.path isEqual:kEMMCallbackPath]) {
  152. return [self handleDevicePolicyAppURL:url];
  153. }
  154. return NO;
  155. }
  156. - (BOOL)hasPreviousSignIn {
  157. if ([_currentUser.authState isAuthorized]) {
  158. return YES;
  159. }
  160. OIDAuthState *authState = [self loadAuthState];
  161. return [authState isAuthorized];
  162. }
  163. - (void)restorePreviousSignInWithCompletion:(nullable void (^)(GIDGoogleUser *_Nullable user,
  164. NSError *_Nullable error))completion {
  165. [self signInWithOptions:[GIDSignInInternalOptions silentOptionsWithCompletion:
  166. ^(GIDSignInResult *signInResult, NSError *error) {
  167. if (signInResult) {
  168. completion(signInResult.user, nil);
  169. } else {
  170. completion(nil, error);
  171. }
  172. }]];
  173. }
  174. - (BOOL)restorePreviousSignInNoRefresh {
  175. if (_currentUser) {
  176. return YES;
  177. }
  178. // Try retrieving an authorization object from the keychain.
  179. OIDAuthState *authState = [self loadAuthState];
  180. if (!authState) {
  181. return NO;
  182. }
  183. // Restore current user without refreshing the access token.
  184. OIDIDToken *idToken =
  185. [[OIDIDToken alloc] initWithIDTokenString:authState.lastTokenResponse.idToken];
  186. GIDProfileData *profileData = [self profileDataWithIDToken:idToken];
  187. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState profileData:profileData];
  188. self.currentUser = user;
  189. return YES;
  190. }
  191. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  192. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  193. hint:(nullable NSString *)hint
  194. completion:(nullable GIDSignInCompletion)completion {
  195. GIDSignInInternalOptions *options =
  196. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  197. presentingViewController:presentingViewController
  198. loginHint:hint
  199. addScopesFlow:NO
  200. completion:completion];
  201. [self signInWithOptions:options];
  202. }
  203. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  204. hint:(nullable NSString *)hint
  205. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  206. completion:(nullable GIDSignInCompletion)completion {
  207. GIDSignInInternalOptions *options =
  208. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  209. presentingViewController:presentingViewController
  210. loginHint:hint
  211. addScopesFlow:NO
  212. scopes:additionalScopes
  213. completion:completion];
  214. [self signInWithOptions:options];
  215. }
  216. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  217. completion:(nullable GIDSignInCompletion)completion {
  218. [self signInWithPresentingViewController:presentingViewController
  219. hint:nil
  220. completion:completion];
  221. }
  222. - (void)addScopes:(NSArray<NSString *> *)scopes
  223. presentingViewController:(UIViewController *)presentingViewController
  224. completion:(nullable GIDSignInCompletion)completion {
  225. GIDConfiguration *configuration = self.currentUser.configuration;
  226. GIDSignInInternalOptions *options =
  227. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  228. presentingViewController:presentingViewController
  229. loginHint:self.currentUser.profile.email
  230. addScopesFlow:YES
  231. completion:completion];
  232. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  233. NSMutableSet<NSString *> *grantedScopes =
  234. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  235. // Check to see if all requested scopes have already been granted.
  236. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  237. // All requested scopes have already been granted, notify callback of failure.
  238. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  239. code:kGIDSignInErrorCodeScopesAlreadyGranted
  240. userInfo:nil];
  241. if (completion) {
  242. dispatch_async(dispatch_get_main_queue(), ^{
  243. completion(nil, error);
  244. });
  245. }
  246. return;
  247. }
  248. // Use the union of granted and requested scopes.
  249. [grantedScopes unionSet:requestedScopes];
  250. options.scopes = [grantedScopes allObjects];
  251. [self signInWithOptions:options];
  252. }
  253. #elif TARGET_OS_OSX
  254. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  255. hint:(nullable NSString *)hint
  256. completion:(nullable GIDSignInCompletion)completion {
  257. GIDSignInInternalOptions *options =
  258. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  259. presentingWindow:presentingWindow
  260. loginHint:hint
  261. addScopesFlow:NO
  262. completion:completion];
  263. [self signInWithOptions:options];
  264. }
  265. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  266. completion:(nullable GIDSignInCompletion)completion {
  267. [self signInWithPresentingWindow:presentingWindow
  268. hint:nil
  269. completion:completion];
  270. }
  271. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  272. hint:(nullable NSString *)hint
  273. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  274. completion:(nullable GIDSignInCompletion)completion {
  275. GIDSignInInternalOptions *options =
  276. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  277. presentingWindow:presentingWindow
  278. loginHint:hint
  279. addScopesFlow:NO
  280. scopes:additionalScopes
  281. completion:completion];
  282. [self signInWithOptions:options];
  283. }
  284. - (void)addScopes:(NSArray<NSString *> *)scopes
  285. presentingWindow:(NSWindow *)presentingWindow
  286. completion:(nullable GIDSignInCompletion)completion {
  287. GIDConfiguration *configuration = self.currentUser.configuration;
  288. GIDSignInInternalOptions *options =
  289. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  290. presentingWindow:presentingWindow
  291. loginHint:self.currentUser.profile.email
  292. addScopesFlow:YES
  293. completion:completion];
  294. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  295. NSMutableSet<NSString *> *grantedScopes =
  296. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  297. // Check to see if all requested scopes have already been granted.
  298. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  299. // All requested scopes have already been granted, notify callback of failure.
  300. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  301. code:kGIDSignInErrorCodeScopesAlreadyGranted
  302. userInfo:nil];
  303. if (completion) {
  304. dispatch_async(dispatch_get_main_queue(), ^{
  305. completion(nil, error);
  306. });
  307. }
  308. return;
  309. }
  310. // Use the union of granted and requested scopes.
  311. [grantedScopes unionSet:requestedScopes];
  312. options.scopes = [grantedScopes allObjects];
  313. [self signInWithOptions:options];
  314. }
  315. #endif // TARGET_OS_OSX
  316. - (void)signOut {
  317. // Clear the current user if there is one.
  318. if (_currentUser) {
  319. self.currentUser = nil;
  320. }
  321. // Remove all state from the keychain.
  322. [self removeAllKeychainEntries];
  323. }
  324. - (void)disconnectWithCompletion:(nullable GIDDisconnectCompletion)completion {
  325. OIDAuthState *authState = _currentUser.authState;
  326. if (!authState) {
  327. // Even the user is not signed in right now, we still need to remove any token saved in the
  328. // keychain.
  329. authState = [self loadAuthState];
  330. }
  331. // Either access or refresh token would work, but we won't have access token if the auth is
  332. // retrieved from keychain.
  333. NSString *token = authState.lastTokenResponse.accessToken;
  334. if (!token) {
  335. token = authState.lastTokenResponse.refreshToken;
  336. }
  337. if (!token) {
  338. [self signOut];
  339. // Nothing to do here, consider the operation successful.
  340. if (completion) {
  341. dispatch_async(dispatch_get_main_queue(), ^{
  342. completion(nil);
  343. });
  344. }
  345. return;
  346. }
  347. NSString *revokeURLString = [NSString stringWithFormat:kRevokeTokenURLTemplate,
  348. [GIDSignInPreferences googleAuthorizationServer], token];
  349. // Append logging parameter
  350. revokeURLString = [NSString stringWithFormat:@"%@&%@=%@&%@=%@",
  351. revokeURLString,
  352. kSDKVersionLoggingParameter,
  353. GIDVersion(),
  354. kEnvironmentLoggingParameter,
  355. GIDEnvironment()];
  356. NSURL *revokeURL = [NSURL URLWithString:revokeURLString];
  357. [self startFetchURL:revokeURL
  358. fromAuthState:authState
  359. withComment:@"GIDSignIn: revoke tokens"
  360. withCompletionHandler:^(NSData *data, NSError *error) {
  361. // Revoking an already revoked token seems always successful, which helps us here.
  362. if (!error) {
  363. [self signOut];
  364. }
  365. if (completion) {
  366. dispatch_async(dispatch_get_main_queue(), ^{
  367. completion(error);
  368. });
  369. }
  370. }];
  371. }
  372. #pragma mark - Custom getters and setters
  373. + (GIDSignIn *)sharedInstance {
  374. static dispatch_once_t once;
  375. static GIDSignIn *sharedInstance;
  376. dispatch_once(&once, ^{
  377. sharedInstance = [[self alloc] initPrivate];
  378. });
  379. return sharedInstance;
  380. }
  381. #pragma mark - Private methods
  382. - (id)initPrivate {
  383. self = [super init];
  384. if (self) {
  385. // Get the bundle of the current executable.
  386. NSBundle *bundle = NSBundle.mainBundle;
  387. // If we have a bundle, try to set the active configuration from the bundle's Info.plist.
  388. if (bundle) {
  389. _configuration = [GIDSignIn configurationFromBundle:bundle];
  390. }
  391. // Check to see if the 3P app is being run for the first time after a fresh install.
  392. BOOL isFreshInstall = [self isFreshInstall];
  393. // If this is a fresh install, ensure that any pre-existing keychain data is purged.
  394. if (isFreshInstall) {
  395. [self removeAllKeychainEntries];
  396. }
  397. NSString *authorizationEnpointURL = [NSString stringWithFormat:kAuthorizationURLTemplate,
  398. [GIDSignInPreferences googleAuthorizationServer]];
  399. NSString *tokenEndpointURL = [NSString stringWithFormat:kTokenURLTemplate,
  400. [GIDSignInPreferences googleTokenServer]];
  401. _appAuthConfiguration = [[OIDServiceConfiguration alloc]
  402. initWithAuthorizationEndpoint:[NSURL URLWithString:authorizationEnpointURL]
  403. tokenEndpoint:[NSURL URLWithString:tokenEndpointURL]];
  404. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  405. // Perform migration of auth state from old (before 5.0) versions of the SDK if needed.
  406. [GIDAuthStateMigration migrateIfNeededWithTokenURL:_appAuthConfiguration.tokenEndpoint
  407. callbackPath:kBrowserCallbackPath
  408. keychainName:kGTMAppAuthKeychainName
  409. isFreshInstall:isFreshInstall];
  410. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  411. }
  412. return self;
  413. }
  414. // Does sanity check for parameters and then authenticates if necessary.
  415. - (void)signInWithOptions:(GIDSignInInternalOptions *)options {
  416. // Options for continuation are not the options we want to cache. The purpose of caching the
  417. // options in the first place is to provide continuation flows with a starting place from which to
  418. // derive suitable options for the continuation!
  419. if (!options.continuation) {
  420. _currentOptions = options;
  421. }
  422. if (options.interactive) {
  423. // Ensure that a configuration has been provided.
  424. if (!_configuration) {
  425. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  426. [NSException raise:NSInvalidArgumentException
  427. format:@"No active configuration. Make sure GIDClientID is set in Info.plist."];
  428. return;
  429. }
  430. // Explicitly throw exception for missing client ID here. This must come before
  431. // scheme check because schemes rely on reverse client IDs.
  432. [self assertValidParameters];
  433. [self assertValidPresentingViewController];
  434. // If the application does not support the required URL schemes tell the developer so.
  435. GIDSignInCallbackSchemes *schemes =
  436. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  437. NSArray<NSString *> *unsupportedSchemes = [schemes unsupportedSchemes];
  438. if (unsupportedSchemes.count != 0) {
  439. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  440. [NSException raise:NSInvalidArgumentException
  441. format:@"Your app is missing support for the following URL schemes: %@",
  442. [unsupportedSchemes componentsJoinedByString:@", "]];
  443. }
  444. }
  445. // If this is a non-interactive flow, use cached authentication if possible.
  446. if (!options.interactive && _currentUser) {
  447. [_currentUser refreshTokensIfNeededWithCompletion:^(GIDGoogleUser *unused, NSError *error) {
  448. if (error) {
  449. [self authenticateWithOptions:options];
  450. } else {
  451. if (options.completion) {
  452. self->_currentOptions = nil;
  453. dispatch_async(dispatch_get_main_queue(), ^{
  454. GIDSignInResult *signInResult =
  455. [[GIDSignInResult alloc] initWithGoogleUser:self->_currentUser serverAuthCode:nil];
  456. options.completion(signInResult, nil);
  457. });
  458. }
  459. }
  460. }];
  461. } else {
  462. [self authenticateWithOptions:options];
  463. }
  464. }
  465. #pragma mark - Authentication flow
  466. - (void)authenticateInteractivelyWithOptions:(GIDSignInInternalOptions *)options {
  467. GIDSignInCallbackSchemes *schemes =
  468. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  469. NSURL *redirectURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@:%@",
  470. [schemes clientIdentifierScheme],
  471. kBrowserCallbackPath]];
  472. NSString *emmSupport;
  473. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  474. emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  475. #elif TARGET_OS_MACCATALYST || TARGET_OS_OSX
  476. emmSupport = nil;
  477. #endif // TARGET_OS_MACCATALYST || TARGET_OS_OSX
  478. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  479. additionalParameters[kIncludeGrantedScopesParameter] = @"true";
  480. if (options.configuration.serverClientID) {
  481. additionalParameters[kAudienceParameter] = options.configuration.serverClientID;
  482. }
  483. if (options.loginHint) {
  484. additionalParameters[kLoginHintParameter] = options.loginHint;
  485. }
  486. if (options.configuration.hostedDomain) {
  487. additionalParameters[kHostedDomainParameter] = options.configuration.hostedDomain;
  488. }
  489. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  490. [additionalParameters addEntriesFromDictionary:
  491. [GIDEMMSupport parametersWithParameters:options.extraParams
  492. emmSupport:emmSupport
  493. isPasscodeInfoRequired:NO]];
  494. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  495. [additionalParameters addEntriesFromDictionary:options.extraParams];
  496. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  497. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  498. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  499. OIDAuthorizationRequest *request =
  500. [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  501. clientId:options.configuration.clientID
  502. scopes:options.scopes
  503. redirectURL:redirectURL
  504. responseType:OIDResponseTypeCode
  505. additionalParameters:additionalParameters];
  506. _currentAuthorizationFlow = [OIDAuthorizationService
  507. presentAuthorizationRequest:request
  508. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  509. presentingViewController:options.presentingViewController
  510. #elif TARGET_OS_OSX
  511. presentingWindow:options.presentingWindow
  512. #endif // TARGET_OS_OSX
  513. callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  514. NSError *_Nullable error) {
  515. [self processAuthorizationResponse:authorizationResponse
  516. error:error
  517. emmSupport:emmSupport];
  518. }];
  519. }
  520. - (void)processAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse
  521. error:(NSError *)error
  522. emmSupport:(NSString *)emmSupport{
  523. if (_restarting) {
  524. // The auth flow is restarting, so the work here would be performed in the next round.
  525. _restarting = NO;
  526. return;
  527. }
  528. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  529. authFlow.emmSupport = emmSupport;
  530. if (authorizationResponse) {
  531. if (authorizationResponse.authorizationCode.length) {
  532. authFlow.authState = [[OIDAuthState alloc]
  533. initWithAuthorizationResponse:authorizationResponse];
  534. // perform auth code exchange
  535. [self maybeFetchToken:authFlow];
  536. } else {
  537. // There was a failure, convert to appropriate error code.
  538. NSString *errorString;
  539. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  540. NSDictionary<NSString *, NSObject *> *params = authorizationResponse.additionalParameters;
  541. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  542. if (authFlow.emmSupport) {
  543. [authFlow wait];
  544. BOOL isEMMError = [[GIDEMMErrorHandler sharedInstance]
  545. handleErrorFromResponse:params
  546. completion:^{
  547. [authFlow next];
  548. }];
  549. if (isEMMError) {
  550. errorCode = kGIDSignInErrorCodeEMM;
  551. }
  552. }
  553. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  554. errorString = (NSString *)params[kOAuth2ErrorKeyName];
  555. if ([errorString isEqualToString:kOAuth2AccessDenied]) {
  556. errorCode = kGIDSignInErrorCodeCanceled;
  557. }
  558. authFlow.error = [self errorWithString:errorString code:errorCode];
  559. }
  560. } else {
  561. NSString *errorString = [error localizedDescription];
  562. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  563. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow) {
  564. // The user has canceled the flow at the iOS modal dialog.
  565. errorString = kUserCanceledError;
  566. errorCode = kGIDSignInErrorCodeCanceled;
  567. }
  568. authFlow.error = [self errorWithString:errorString code:errorCode];
  569. }
  570. [self addDecodeIdTokenCallback:authFlow];
  571. [self addSaveAuthCallback:authFlow];
  572. [self addCompletionCallback:authFlow];
  573. }
  574. // Perform authentication with the provided options.
  575. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options {
  576. // If this is an interactive flow, we're not going to try to restore any saved auth state.
  577. if (options.interactive) {
  578. [self authenticateInteractivelyWithOptions:options];
  579. return;
  580. }
  581. // Try retrieving an authorization object from the keychain.
  582. OIDAuthState *authState = [self loadAuthState];
  583. if (![authState isAuthorized]) {
  584. // No valid auth in keychain, per documentation/spec, notify callback of failure.
  585. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  586. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  587. userInfo:nil];
  588. if (options.completion) {
  589. _currentOptions = nil;
  590. dispatch_async(dispatch_get_main_queue(), ^{
  591. options.completion(nil, error);
  592. });
  593. }
  594. return;
  595. }
  596. // Complete the auth flow using saved auth in keychain.
  597. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  598. authFlow.authState = authState;
  599. [self maybeFetchToken:authFlow];
  600. [self addDecodeIdTokenCallback:authFlow];
  601. [self addSaveAuthCallback:authFlow];
  602. [self addCompletionCallback:authFlow];
  603. }
  604. // Fetches the access token if necessary as part of the auth flow.
  605. - (void)maybeFetchToken:(GIDAuthFlow *)authFlow {
  606. OIDAuthState *authState = authFlow.authState;
  607. // Do nothing if we have an auth flow error or a restored access token that isn't near expiration.
  608. if (authFlow.error ||
  609. (authState.lastTokenResponse.accessToken &&
  610. [authState.lastTokenResponse.accessTokenExpirationDate timeIntervalSinceNow] >
  611. kMinimumRestoredAccessTokenTimeToExpire)) {
  612. return;
  613. }
  614. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  615. if (_currentOptions.configuration.serverClientID) {
  616. additionalParameters[kAudienceParameter] = _currentOptions.configuration.serverClientID;
  617. }
  618. if (_currentOptions.configuration.openIDRealm) {
  619. additionalParameters[kOpenIDRealmParameter] = _currentOptions.configuration.openIDRealm;
  620. }
  621. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  622. NSDictionary<NSString *, NSObject *> *params =
  623. authState.lastAuthorizationResponse.additionalParameters;
  624. NSString *passcodeInfoRequired = (NSString *)params[kEMMPasscodeInfoRequiredKeyName];
  625. [additionalParameters addEntriesFromDictionary:
  626. [GIDEMMSupport parametersWithParameters:@{}
  627. emmSupport:authFlow.emmSupport
  628. isPasscodeInfoRequired:passcodeInfoRequired.length > 0]];
  629. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  630. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  631. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  632. OIDTokenRequest *tokenRequest;
  633. if (!authState.lastTokenResponse.accessToken &&
  634. authState.lastAuthorizationResponse.authorizationCode) {
  635. tokenRequest = [authState.lastAuthorizationResponse
  636. tokenExchangeRequestWithAdditionalParameters:additionalParameters];
  637. } else {
  638. [additionalParameters
  639. addEntriesFromDictionary:authState.lastTokenResponse.request.additionalParameters];
  640. tokenRequest = [authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  641. }
  642. [authFlow wait];
  643. [OIDAuthorizationService
  644. performTokenRequest:tokenRequest
  645. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  646. NSError *_Nullable error) {
  647. [authState updateWithTokenResponse:tokenResponse error:error];
  648. authFlow.error = error;
  649. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  650. if (authFlow.emmSupport) {
  651. [GIDEMMSupport handleTokenFetchEMMError:error completion:^(NSError *error) {
  652. authFlow.error = error;
  653. [authFlow next];
  654. }];
  655. } else {
  656. [authFlow next];
  657. }
  658. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  659. [authFlow next];
  660. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  661. }];
  662. }
  663. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  664. - (void)addSaveAuthCallback:(GIDAuthFlow *)authFlow {
  665. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  666. [authFlow addCallback:^() {
  667. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  668. OIDAuthState *authState = handlerAuthFlow.authState;
  669. if (authState && !handlerAuthFlow.error) {
  670. if (![self saveAuthState:authState]) {
  671. handlerAuthFlow.error = [self errorWithString:kKeychainError
  672. code:kGIDSignInErrorCodeKeychain];
  673. return;
  674. }
  675. if (self->_currentOptions.addScopesFlow) {
  676. [self->_currentUser updateWithTokenResponse:authState.lastTokenResponse
  677. authorizationResponse:authState.lastAuthorizationResponse
  678. profileData:handlerAuthFlow.profileData];
  679. } else {
  680. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState
  681. profileData:handlerAuthFlow.profileData];
  682. self.currentUser = user;
  683. }
  684. }
  685. }];
  686. }
  687. // Adds a callback to the auth flow to extract user data from the ID token where available and
  688. // make a userinfo request if necessary.
  689. - (void)addDecodeIdTokenCallback:(GIDAuthFlow *)authFlow {
  690. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  691. [authFlow addCallback:^() {
  692. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  693. OIDAuthState *authState = handlerAuthFlow.authState;
  694. if (!authState || handlerAuthFlow.error) {
  695. return;
  696. }
  697. OIDIDToken *idToken =
  698. [[OIDIDToken alloc] initWithIDTokenString: authState.lastTokenResponse.idToken];
  699. // If the profile data are present in the ID token, use them.
  700. if (idToken) {
  701. handlerAuthFlow.profileData = [self profileDataWithIDToken:idToken];
  702. }
  703. // If we can't retrieve profile data from the ID token, make a userInfo request to fetch them.
  704. if (!handlerAuthFlow.profileData) {
  705. [handlerAuthFlow wait];
  706. NSURL *infoURL = [NSURL URLWithString:
  707. [NSString stringWithFormat:kUserInfoURLTemplate,
  708. [GIDSignInPreferences googleUserInfoServer],
  709. authState.lastTokenResponse.accessToken]];
  710. [self startFetchURL:infoURL
  711. fromAuthState:authState
  712. withComment:@"GIDSignIn: fetch basic profile info"
  713. withCompletionHandler:^(NSData *data, NSError *error) {
  714. if (data && !error) {
  715. NSError *jsonDeserializationError;
  716. NSDictionary<NSString *, NSString *> *profileDict =
  717. [NSJSONSerialization JSONObjectWithData:data
  718. options:NSJSONReadingMutableContainers
  719. error:&jsonDeserializationError];
  720. if (profileDict) {
  721. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  722. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  723. name:profileDict[kBasicProfileNameKey]
  724. givenName:profileDict[kBasicProfileGivenNameKey]
  725. familyName:profileDict[kBasicProfileFamilyNameKey]
  726. imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
  727. }
  728. }
  729. if (error) {
  730. handlerAuthFlow.error = error;
  731. }
  732. [handlerAuthFlow next];
  733. }];
  734. }
  735. }];
  736. }
  737. // Adds a callback to the auth flow to complete the flow by calling the sign-in callback.
  738. - (void)addCompletionCallback:(GIDAuthFlow *)authFlow {
  739. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  740. [authFlow addCallback:^() {
  741. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  742. if (self->_currentOptions.completion) {
  743. GIDSignInCompletion completion = self->_currentOptions.completion;
  744. self->_currentOptions = nil;
  745. dispatch_async(dispatch_get_main_queue(), ^{
  746. if (handlerAuthFlow.error) {
  747. completion(nil, handlerAuthFlow.error);
  748. } else {
  749. OIDAuthState *authState = handlerAuthFlow.authState;
  750. NSString *_Nullable serverAuthCode =
  751. [authState.lastTokenResponse.additionalParameters[@"server_code"] copy];
  752. GIDSignInResult *signInResult =
  753. [[GIDSignInResult alloc] initWithGoogleUser:self->_currentUser
  754. serverAuthCode:serverAuthCode];
  755. completion(signInResult, nil);
  756. }
  757. });
  758. }
  759. }];
  760. }
  761. - (void)startFetchURL:(NSURL *)URL
  762. fromAuthState:(OIDAuthState *)authState
  763. withComment:(NSString *)comment
  764. withCompletionHandler:(void (^)(NSData *, NSError *))handler {
  765. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  766. GTMSessionFetcher *fetcher;
  767. GTMAppAuthFetcherAuthorization *authorization =
  768. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  769. id<GTMSessionFetcherServiceProtocol> fetcherService = authorization.fetcherService;
  770. if (fetcherService) {
  771. fetcher = [fetcherService fetcherWithRequest:request];
  772. } else {
  773. fetcher = [GTMSessionFetcher fetcherWithRequest:request];
  774. }
  775. fetcher.retryEnabled = YES;
  776. fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
  777. fetcher.comment = comment;
  778. [fetcher beginFetchWithCompletionHandler:handler];
  779. }
  780. // Parse incoming URL from the Google Device Policy app.
  781. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  782. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  783. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  784. NSObject<NSCopying> *actionParam = params[@"action"];
  785. NSString *actionString =
  786. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  787. if (![@"restart_auth" isEqualToString:actionString]) {
  788. return NO;
  789. }
  790. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  791. if (!_currentOptions.presentingViewController) {
  792. return NO;
  793. }
  794. #elif TARGET_OS_OSX
  795. if (!_currentOptions.presentingWindow) {
  796. return NO;
  797. }
  798. #endif // TARGET_OS_OSX
  799. if (!_currentAuthorizationFlow) {
  800. return NO;
  801. }
  802. _restarting = YES;
  803. [_currentAuthorizationFlow cancel];
  804. _currentAuthorizationFlow = nil;
  805. _restarting = NO;
  806. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  807. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  808. // so we need to wait until the previous presentation is completely gone to ensure the right
  809. // anchor window is used here.
  810. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  811. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  812. dispatch_get_main_queue(), ^{
  813. [self signInWithOptions:[self->_currentOptions optionsWithExtraParameters:extraParameters
  814. forContinuation:YES]];
  815. });
  816. return YES;
  817. }
  818. #pragma mark - Helpers
  819. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  820. if (errorString == nil) {
  821. errorString = @"Unknown error";
  822. }
  823. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  824. return [NSError errorWithDomain:kGIDSignInErrorDomain
  825. code:code
  826. userInfo:errorDict];
  827. }
  828. + (BOOL)isOperatingSystemAtLeast9 {
  829. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  830. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  831. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  832. }
  833. // Asserts the parameters being valid.
  834. - (void)assertValidParameters {
  835. if (![_currentOptions.configuration.clientID length]) {
  836. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  837. [NSException raise:NSInvalidArgumentException
  838. format:@"You must specify |clientID| in |GIDConfiguration|"];
  839. }
  840. }
  841. // Assert that the presenting view controller has been set.
  842. - (void)assertValidPresentingViewController {
  843. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  844. if (!_currentOptions.presentingViewController)
  845. #elif TARGET_OS_OSX
  846. if (!_currentOptions.presentingWindow)
  847. #endif // TARGET_OS_OSX
  848. {
  849. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  850. [NSException raise:NSInvalidArgumentException
  851. format:@"|presentingViewController| must be set."];
  852. }
  853. }
  854. // Checks whether or not this is the first time the app runs.
  855. - (BOOL)isFreshInstall {
  856. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  857. if ([defaults boolForKey:kAppHasRunBeforeKey]) {
  858. return NO;
  859. }
  860. [defaults setBool:YES forKey:kAppHasRunBeforeKey];
  861. return YES;
  862. }
  863. - (void)removeAllKeychainEntries {
  864. [GTMAppAuthFetcherAuthorization removeAuthorizationFromKeychainForName:kGTMAppAuthKeychainName
  865. useDataProtectionKeychain:YES];
  866. }
  867. - (BOOL)saveAuthState:(OIDAuthState *)authState {
  868. GTMAppAuthFetcherAuthorization *authorization =
  869. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  870. return [GTMAppAuthFetcherAuthorization saveAuthorization:authorization
  871. toKeychainForName:kGTMAppAuthKeychainName
  872. useDataProtectionKeychain:YES];
  873. }
  874. - (OIDAuthState *)loadAuthState {
  875. GTMAppAuthFetcherAuthorization *authorization =
  876. [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:kGTMAppAuthKeychainName
  877. useDataProtectionKeychain:YES];
  878. return authorization.authState;
  879. }
  880. // Generates user profile from OIDIDToken.
  881. - (GIDProfileData *)profileDataWithIDToken:(OIDIDToken *)idToken {
  882. if (!idToken ||
  883. !idToken.claims[kBasicProfilePictureKey] ||
  884. !idToken.claims[kBasicProfileNameKey] ||
  885. !idToken.claims[kBasicProfileGivenNameKey] ||
  886. !idToken.claims[kBasicProfileFamilyNameKey]) {
  887. return nil;
  888. }
  889. return [[GIDProfileData alloc]
  890. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  891. name:idToken.claims[kBasicProfileNameKey]
  892. givenName:idToken.claims[kBasicProfileGivenNameKey]
  893. familyName:idToken.claims[kBasicProfileFamilyNameKey]
  894. imageURL:[NSURL URLWithString:idToken.claims[kBasicProfilePictureKey]]];
  895. }
  896. // Try to retrieve a configuration value from an |NSBundle|'s Info.plist for a given key.
  897. + (nullable NSString *)configValueFromBundle:(NSBundle *)bundle forKey:(NSString *)key {
  898. NSString *value;
  899. id configValue = [bundle objectForInfoDictionaryKey:key];
  900. if ([configValue isKindOfClass:[NSString class]]) {
  901. value = configValue;
  902. }
  903. return value;
  904. }
  905. // Try to generate a |GIDConfiguration| from an |NSBundle|'s Info.plist.
  906. + (nullable GIDConfiguration *)configurationFromBundle:(NSBundle *)bundle {
  907. GIDConfiguration *configuration;
  908. // Retrieve any valid config parameters from the bundle's Info.plist.
  909. NSString *clientID = [GIDSignIn configValueFromBundle:bundle forKey:kConfigClientIDKey];
  910. NSString *serverClientID = [GIDSignIn configValueFromBundle:bundle
  911. forKey:kConfigServerClientIDKey];
  912. NSString *hostedDomain = [GIDSignIn configValueFromBundle:bundle forKey:kConfigHostedDomainKey];
  913. NSString *openIDRealm = [GIDSignIn configValueFromBundle:bundle forKey:kConfigOpenIDRealmKey];
  914. // If we have at least a client ID, try to construct a configuration.
  915. if (clientID) {
  916. configuration = [[GIDConfiguration alloc] initWithClientID:clientID
  917. serverClientID:serverClientID
  918. hostedDomain:hostedDomain
  919. openIDRealm:openIDRealm];
  920. }
  921. return configuration;
  922. }
  923. @end
  924. NS_ASSUME_NONNULL_END