GIDSignIn.m 42 KB

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