GIDSignIn.m 42 KB

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