GIDSignIn.m 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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. @import GTMAppAuth;
  34. #ifdef SWIFT_PACKAGE
  35. @import AppAuth;
  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 <GTMSessionFetcher/GTMSessionFetcher.h>
  51. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  52. #import <AppAuth/OIDAuthorizationService+IOS.h>
  53. #elif TARGET_OS_OSX
  54. #import <AppAuth/OIDAuthorizationService+Mac.h>
  55. #endif
  56. #endif
  57. NS_ASSUME_NONNULL_BEGIN
  58. // The name of the query parameter used for logging the restart of auth from EMM callback.
  59. static NSString *const kEMMRestartAuthParameter = @"emmres";
  60. // The URL template for the authorization endpoint.
  61. static NSString *const kAuthorizationURLTemplate = @"https://%@/o/oauth2/v2/auth";
  62. // The URL template for the token endpoint.
  63. static NSString *const kTokenURLTemplate = @"https://%@/token";
  64. // The URL template for the URL to get user info.
  65. static NSString *const kUserInfoURLTemplate = @"https://%@/oauth2/v3/userinfo?access_token=%@";
  66. // The URL template for the URL to revoke the token.
  67. static NSString *const kRevokeTokenURLTemplate = @"https://%@/o/oauth2/revoke?token=%@";
  68. // Expected path in the URL scheme to be handled.
  69. static NSString *const kBrowserCallbackPath = @"/oauth2callback";
  70. // Expected path for EMM callback.
  71. static NSString *const kEMMCallbackPath = @"/emmcallback";
  72. // The EMM support version
  73. static NSString *const kEMMVersion = @"1";
  74. // The error code for Google Identity.
  75. NSErrorDomain const kGIDSignInErrorDomain = @"com.google.GIDSignIn";
  76. // Keychain constants for saving state in the authentication flow.
  77. static NSString *const kGTMAppAuthKeychainName = @"auth";
  78. // Basic profile (Fat ID Token / userinfo endpoint) keys
  79. static NSString *const kBasicProfileEmailKey = @"email";
  80. static NSString *const kBasicProfilePictureKey = @"picture";
  81. static NSString *const kBasicProfileNameKey = @"name";
  82. static NSString *const kBasicProfileGivenNameKey = @"given_name";
  83. static NSString *const kBasicProfileFamilyNameKey = @"family_name";
  84. // Parameters in the callback URL coming back from browser.
  85. static NSString *const kAuthorizationCodeKeyName = @"code";
  86. static NSString *const kOAuth2ErrorKeyName = @"error";
  87. static NSString *const kOAuth2AccessDenied = @"access_denied";
  88. static NSString *const kEMMPasscodeInfoRequiredKeyName = @"emm_passcode_info_required";
  89. // Error string for unavailable keychain.
  90. static NSString *const kKeychainError = @"keychain error";
  91. // Error string for user cancelations.
  92. static NSString *const kUserCanceledError = @"The user canceled the sign-in flow.";
  93. // User preference key to detect fresh install of the app.
  94. static NSString *const kAppHasRunBeforeKey = @"GID_AppHasRunBefore";
  95. // Maximum retry interval in seconds for the fetcher.
  96. static const NSTimeInterval kFetcherMaxRetryInterval = 15.0;
  97. // The delay before the new sign-in flow can be presented after the existing one is cancelled.
  98. static const NSTimeInterval kPresentationDelayAfterCancel = 1.0;
  99. // Parameters for the auth and token exchange endpoints.
  100. static NSString *const kAudienceParameter = @"audience";
  101. // See b/11669751 .
  102. static NSString *const kOpenIDRealmParameter = @"openid.realm";
  103. static NSString *const kIncludeGrantedScopesParameter = @"include_granted_scopes";
  104. static NSString *const kLoginHintParameter = @"login_hint";
  105. static NSString *const kHostedDomainParameter = @"hd";
  106. // Minimum time to expiration for a restored access token.
  107. static const NSTimeInterval kMinimumRestoredAccessTokenTimeToExpire = 600.0;
  108. // Info.plist config keys
  109. static NSString *const kConfigClientIDKey = @"GIDClientID";
  110. static NSString *const kConfigServerClientIDKey = @"GIDServerClientID";
  111. static NSString *const kConfigHostedDomainKey = @"GIDHostedDomain";
  112. static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
  113. // The callback queue used for authentication flow.
  114. @interface GIDAuthFlow : GIDCallbackQueue
  115. @property(nonatomic, strong, nullable) OIDAuthState *authState;
  116. @property(nonatomic, strong, nullable) NSError *error;
  117. @property(nonatomic, copy, nullable) NSString *emmSupport;
  118. @property(nonatomic, nullable) GIDProfileData *profileData;
  119. @end
  120. @implementation GIDAuthFlow
  121. @end
  122. @implementation GIDSignIn {
  123. // This value is used when sign-in flows are resumed via the handling of a URL. Its value is
  124. // set when a sign-in flow is begun via |signInWithOptions:| when the options passed don't
  125. // represent a sign in continuation.
  126. GIDSignInInternalOptions *_currentOptions;
  127. // AppAuth configuration object.
  128. OIDServiceConfiguration *_appAuthConfiguration;
  129. // AppAuth external user-agent session state.
  130. id<OIDExternalUserAgentSession> _currentAuthorizationFlow;
  131. // Flag to indicate that the auth flow is restarting.
  132. BOOL _restarting;
  133. // Keychain manager for GTMAppAuth
  134. GTMKeychainStore *_keychainStore;
  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. - (instancetype)initWithKeychainStore:(GTMKeychainStore *)keychainStore {
  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. _keychainStore = keychainStore;
  408. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  409. // Perform migration of auth state from old (before 5.0) versions of the SDK if needed.
  410. GIDAuthStateMigration *migration =
  411. [[GIDAuthStateMigration alloc] initWithKeychainStore:_keychainStore];
  412. [migration migrateIfNeededWithTokenURL:_appAuthConfiguration.tokenEndpoint
  413. callbackPath:kBrowserCallbackPath
  414. keychainName:kGTMAppAuthKeychainName
  415. isFreshInstall:isFreshInstall];
  416. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  417. }
  418. return self;
  419. }
  420. - (instancetype)initPrivate {
  421. GTMKeychainStore *keychainStore =
  422. [[GTMKeychainStore alloc] initWithItemName:kGTMAppAuthKeychainName];
  423. return [self initWithKeychainStore:keychainStore];
  424. }
  425. // Does sanity check for parameters and then authenticates if necessary.
  426. - (void)signInWithOptions:(GIDSignInInternalOptions *)options {
  427. // Options for continuation are not the options we want to cache. The purpose of caching the
  428. // options in the first place is to provide continuation flows with a starting place from which to
  429. // derive suitable options for the continuation!
  430. if (!options.continuation) {
  431. _currentOptions = options;
  432. }
  433. if (options.interactive) {
  434. // Ensure that a configuration has been provided.
  435. if (!_configuration) {
  436. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  437. [NSException raise:NSInvalidArgumentException
  438. format:@"No active configuration. Make sure GIDClientID is set in Info.plist."];
  439. return;
  440. }
  441. // Explicitly throw exception for missing client ID here. This must come before
  442. // scheme check because schemes rely on reverse client IDs.
  443. [self assertValidParameters];
  444. [self assertValidPresentingViewController];
  445. // If the application does not support the required URL schemes tell the developer so.
  446. GIDSignInCallbackSchemes *schemes =
  447. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  448. NSArray<NSString *> *unsupportedSchemes = [schemes unsupportedSchemes];
  449. if (unsupportedSchemes.count != 0) {
  450. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  451. [NSException raise:NSInvalidArgumentException
  452. format:@"Your app is missing support for the following URL schemes: %@",
  453. [unsupportedSchemes componentsJoinedByString:@", "]];
  454. }
  455. }
  456. // If this is a non-interactive flow, use cached authentication if possible.
  457. if (!options.interactive && _currentUser) {
  458. [_currentUser refreshTokensIfNeededWithCompletion:^(GIDGoogleUser *unused, NSError *error) {
  459. if (error) {
  460. [self authenticateWithOptions:options];
  461. } else {
  462. if (options.completion) {
  463. self->_currentOptions = nil;
  464. dispatch_async(dispatch_get_main_queue(), ^{
  465. GIDSignInResult *signInResult =
  466. [[GIDSignInResult alloc] initWithGoogleUser:self->_currentUser serverAuthCode:nil];
  467. options.completion(signInResult, nil);
  468. });
  469. }
  470. }
  471. }];
  472. } else {
  473. [self authenticateWithOptions:options];
  474. }
  475. }
  476. #pragma mark - Authentication flow
  477. - (void)authenticateInteractivelyWithOptions:(GIDSignInInternalOptions *)options {
  478. GIDSignInCallbackSchemes *schemes =
  479. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  480. NSURL *redirectURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@:%@",
  481. [schemes clientIdentifierScheme],
  482. kBrowserCallbackPath]];
  483. NSString *emmSupport;
  484. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  485. emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  486. #elif TARGET_OS_MACCATALYST || TARGET_OS_OSX
  487. emmSupport = nil;
  488. #endif // TARGET_OS_MACCATALYST || TARGET_OS_OSX
  489. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  490. additionalParameters[kIncludeGrantedScopesParameter] = @"true";
  491. if (options.configuration.serverClientID) {
  492. additionalParameters[kAudienceParameter] = options.configuration.serverClientID;
  493. }
  494. if (options.loginHint) {
  495. additionalParameters[kLoginHintParameter] = options.loginHint;
  496. }
  497. if (options.configuration.hostedDomain) {
  498. additionalParameters[kHostedDomainParameter] = options.configuration.hostedDomain;
  499. }
  500. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  501. [additionalParameters addEntriesFromDictionary:
  502. [GIDEMMSupport parametersWithParameters:options.extraParams
  503. emmSupport:emmSupport
  504. isPasscodeInfoRequired:NO]];
  505. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  506. [additionalParameters addEntriesFromDictionary:options.extraParams];
  507. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  508. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  509. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  510. OIDAuthorizationRequest *request =
  511. [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  512. clientId:options.configuration.clientID
  513. scopes:options.scopes
  514. redirectURL:redirectURL
  515. responseType:OIDResponseTypeCode
  516. additionalParameters:additionalParameters];
  517. _currentAuthorizationFlow = [OIDAuthorizationService
  518. presentAuthorizationRequest:request
  519. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  520. presentingViewController:options.presentingViewController
  521. #elif TARGET_OS_OSX
  522. presentingWindow:options.presentingWindow
  523. #endif // TARGET_OS_OSX
  524. callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  525. NSError *_Nullable error) {
  526. [self processAuthorizationResponse:authorizationResponse
  527. error:error
  528. emmSupport:emmSupport];
  529. }];
  530. }
  531. - (void)processAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse
  532. error:(NSError *)error
  533. emmSupport:(NSString *)emmSupport{
  534. if (_restarting) {
  535. // The auth flow is restarting, so the work here would be performed in the next round.
  536. _restarting = NO;
  537. return;
  538. }
  539. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  540. authFlow.emmSupport = emmSupport;
  541. if (authorizationResponse) {
  542. if (authorizationResponse.authorizationCode.length) {
  543. authFlow.authState = [[OIDAuthState alloc]
  544. initWithAuthorizationResponse:authorizationResponse];
  545. // perform auth code exchange
  546. [self maybeFetchToken:authFlow];
  547. } else {
  548. // There was a failure, convert to appropriate error code.
  549. NSString *errorString;
  550. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  551. NSDictionary<NSString *, NSObject *> *params = authorizationResponse.additionalParameters;
  552. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  553. if (authFlow.emmSupport) {
  554. [authFlow wait];
  555. BOOL isEMMError = [[GIDEMMErrorHandler sharedInstance]
  556. handleErrorFromResponse:params
  557. completion:^{
  558. [authFlow next];
  559. }];
  560. if (isEMMError) {
  561. errorCode = kGIDSignInErrorCodeEMM;
  562. }
  563. }
  564. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  565. errorString = (NSString *)params[kOAuth2ErrorKeyName];
  566. if ([errorString isEqualToString:kOAuth2AccessDenied]) {
  567. errorCode = kGIDSignInErrorCodeCanceled;
  568. }
  569. authFlow.error = [self errorWithString:errorString code:errorCode];
  570. }
  571. } else {
  572. NSString *errorString = [error localizedDescription];
  573. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  574. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow) {
  575. // The user has canceled the flow at the iOS modal dialog.
  576. errorString = kUserCanceledError;
  577. errorCode = kGIDSignInErrorCodeCanceled;
  578. }
  579. authFlow.error = [self errorWithString:errorString code:errorCode];
  580. }
  581. [self addDecodeIdTokenCallback:authFlow];
  582. [self addSaveAuthCallback:authFlow];
  583. [self addCompletionCallback:authFlow];
  584. }
  585. // Perform authentication with the provided options.
  586. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options {
  587. // If this is an interactive flow, we're not going to try to restore any saved auth state.
  588. if (options.interactive) {
  589. [self authenticateInteractivelyWithOptions:options];
  590. return;
  591. }
  592. // Try retrieving an authorization object from the keychain.
  593. OIDAuthState *authState = [self loadAuthState];
  594. if (![authState isAuthorized]) {
  595. // No valid auth in keychain, per documentation/spec, notify callback of failure.
  596. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  597. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  598. userInfo:nil];
  599. if (options.completion) {
  600. _currentOptions = nil;
  601. dispatch_async(dispatch_get_main_queue(), ^{
  602. options.completion(nil, error);
  603. });
  604. }
  605. return;
  606. }
  607. // Complete the auth flow using saved auth in keychain.
  608. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  609. authFlow.authState = authState;
  610. [self maybeFetchToken:authFlow];
  611. [self addDecodeIdTokenCallback:authFlow];
  612. [self addSaveAuthCallback:authFlow];
  613. [self addCompletionCallback:authFlow];
  614. }
  615. // Fetches the access token if necessary as part of the auth flow.
  616. - (void)maybeFetchToken:(GIDAuthFlow *)authFlow {
  617. OIDAuthState *authState = authFlow.authState;
  618. // Do nothing if we have an auth flow error or a restored access token that isn't near expiration.
  619. if (authFlow.error ||
  620. (authState.lastTokenResponse.accessToken &&
  621. [authState.lastTokenResponse.accessTokenExpirationDate timeIntervalSinceNow] >
  622. kMinimumRestoredAccessTokenTimeToExpire)) {
  623. return;
  624. }
  625. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  626. if (_currentOptions.configuration.serverClientID) {
  627. additionalParameters[kAudienceParameter] = _currentOptions.configuration.serverClientID;
  628. }
  629. if (_currentOptions.configuration.openIDRealm) {
  630. additionalParameters[kOpenIDRealmParameter] = _currentOptions.configuration.openIDRealm;
  631. }
  632. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  633. NSDictionary<NSString *, NSObject *> *params =
  634. authState.lastAuthorizationResponse.additionalParameters;
  635. NSString *passcodeInfoRequired = (NSString *)params[kEMMPasscodeInfoRequiredKeyName];
  636. [additionalParameters addEntriesFromDictionary:
  637. [GIDEMMSupport parametersWithParameters:@{}
  638. emmSupport:authFlow.emmSupport
  639. isPasscodeInfoRequired:passcodeInfoRequired.length > 0]];
  640. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  641. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  642. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  643. OIDTokenRequest *tokenRequest;
  644. if (!authState.lastTokenResponse.accessToken &&
  645. authState.lastAuthorizationResponse.authorizationCode) {
  646. tokenRequest = [authState.lastAuthorizationResponse
  647. tokenExchangeRequestWithAdditionalParameters:additionalParameters];
  648. } else {
  649. [additionalParameters
  650. addEntriesFromDictionary:authState.lastTokenResponse.request.additionalParameters];
  651. tokenRequest = [authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  652. }
  653. [authFlow wait];
  654. [OIDAuthorizationService
  655. performTokenRequest:tokenRequest
  656. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  657. NSError *_Nullable error) {
  658. [authState updateWithTokenResponse:tokenResponse error:error];
  659. authFlow.error = error;
  660. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  661. if (authFlow.emmSupport) {
  662. [GIDEMMSupport handleTokenFetchEMMError:error completion:^(NSError *error) {
  663. authFlow.error = error;
  664. [authFlow next];
  665. }];
  666. } else {
  667. [authFlow next];
  668. }
  669. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  670. [authFlow next];
  671. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  672. }];
  673. }
  674. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  675. - (void)addSaveAuthCallback:(GIDAuthFlow *)authFlow {
  676. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  677. [authFlow addCallback:^() {
  678. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  679. OIDAuthState *authState = handlerAuthFlow.authState;
  680. if (authState && !handlerAuthFlow.error) {
  681. if (![self saveAuthState:authState]) {
  682. handlerAuthFlow.error = [self errorWithString:kKeychainError
  683. code:kGIDSignInErrorCodeKeychain];
  684. return;
  685. }
  686. if (self->_currentOptions.addScopesFlow) {
  687. [self->_currentUser updateWithTokenResponse:authState.lastTokenResponse
  688. authorizationResponse:authState.lastAuthorizationResponse
  689. profileData:handlerAuthFlow.profileData];
  690. } else {
  691. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState
  692. profileData:handlerAuthFlow.profileData];
  693. self.currentUser = user;
  694. }
  695. }
  696. }];
  697. }
  698. // Adds a callback to the auth flow to extract user data from the ID token where available and
  699. // make a userinfo request if necessary.
  700. - (void)addDecodeIdTokenCallback:(GIDAuthFlow *)authFlow {
  701. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  702. [authFlow addCallback:^() {
  703. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  704. OIDAuthState *authState = handlerAuthFlow.authState;
  705. if (!authState || handlerAuthFlow.error) {
  706. return;
  707. }
  708. OIDIDToken *idToken =
  709. [[OIDIDToken alloc] initWithIDTokenString: authState.lastTokenResponse.idToken];
  710. // If the profile data are present in the ID token, use them.
  711. if (idToken) {
  712. handlerAuthFlow.profileData = [self profileDataWithIDToken:idToken];
  713. }
  714. // If we can't retrieve profile data from the ID token, make a userInfo request to fetch them.
  715. if (!handlerAuthFlow.profileData) {
  716. [handlerAuthFlow wait];
  717. NSURL *infoURL = [NSURL URLWithString:
  718. [NSString stringWithFormat:kUserInfoURLTemplate,
  719. [GIDSignInPreferences googleUserInfoServer],
  720. authState.lastTokenResponse.accessToken]];
  721. [self startFetchURL:infoURL
  722. fromAuthState:authState
  723. withComment:@"GIDSignIn: fetch basic profile info"
  724. withCompletionHandler:^(NSData *data, NSError *error) {
  725. if (data && !error) {
  726. NSError *jsonDeserializationError;
  727. NSDictionary<NSString *, NSString *> *profileDict =
  728. [NSJSONSerialization JSONObjectWithData:data
  729. options:NSJSONReadingMutableContainers
  730. error:&jsonDeserializationError];
  731. if (profileDict) {
  732. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  733. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  734. name:profileDict[kBasicProfileNameKey]
  735. givenName:profileDict[kBasicProfileGivenNameKey]
  736. familyName:profileDict[kBasicProfileFamilyNameKey]
  737. imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
  738. }
  739. }
  740. if (error) {
  741. handlerAuthFlow.error = error;
  742. }
  743. [handlerAuthFlow next];
  744. }];
  745. }
  746. }];
  747. }
  748. // Adds a callback to the auth flow to complete the flow by calling the sign-in callback.
  749. - (void)addCompletionCallback:(GIDAuthFlow *)authFlow {
  750. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  751. [authFlow addCallback:^() {
  752. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  753. if (self->_currentOptions.completion) {
  754. GIDSignInCompletion completion = self->_currentOptions.completion;
  755. self->_currentOptions = nil;
  756. dispatch_async(dispatch_get_main_queue(), ^{
  757. if (handlerAuthFlow.error) {
  758. completion(nil, handlerAuthFlow.error);
  759. } else {
  760. OIDAuthState *authState = handlerAuthFlow.authState;
  761. NSString *_Nullable serverAuthCode =
  762. [authState.lastTokenResponse.additionalParameters[@"server_code"] copy];
  763. GIDSignInResult *signInResult =
  764. [[GIDSignInResult alloc] initWithGoogleUser:self->_currentUser
  765. serverAuthCode:serverAuthCode];
  766. completion(signInResult, nil);
  767. }
  768. });
  769. }
  770. }];
  771. }
  772. - (void)startFetchURL:(NSURL *)URL
  773. fromAuthState:(OIDAuthState *)authState
  774. withComment:(NSString *)comment
  775. withCompletionHandler:(void (^)(NSData *, NSError *))handler {
  776. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  777. GTMSessionFetcher *fetcher;
  778. GTMAuthSession *authorization = [[GTMAuthSession alloc] initWithAuthState:authState];
  779. id<GTMSessionFetcherServiceProtocol> fetcherService = authorization.fetcherService;
  780. if (fetcherService) {
  781. fetcher = [fetcherService fetcherWithRequest:request];
  782. } else {
  783. fetcher = [GTMSessionFetcher fetcherWithRequest:request];
  784. }
  785. fetcher.retryEnabled = YES;
  786. fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
  787. fetcher.comment = comment;
  788. [fetcher beginFetchWithCompletionHandler:handler];
  789. }
  790. // Parse incoming URL from the Google Device Policy app.
  791. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  792. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  793. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  794. NSObject<NSCopying> *actionParam = params[@"action"];
  795. NSString *actionString =
  796. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  797. if (![@"restart_auth" isEqualToString:actionString]) {
  798. return NO;
  799. }
  800. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  801. if (!_currentOptions.presentingViewController) {
  802. return NO;
  803. }
  804. #elif TARGET_OS_OSX
  805. if (!_currentOptions.presentingWindow) {
  806. return NO;
  807. }
  808. #endif // TARGET_OS_OSX
  809. if (!_currentAuthorizationFlow) {
  810. return NO;
  811. }
  812. _restarting = YES;
  813. [_currentAuthorizationFlow cancel];
  814. _currentAuthorizationFlow = nil;
  815. _restarting = NO;
  816. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  817. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  818. // so we need to wait until the previous presentation is completely gone to ensure the right
  819. // anchor window is used here.
  820. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  821. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  822. dispatch_get_main_queue(), ^{
  823. [self signInWithOptions:[self->_currentOptions optionsWithExtraParameters:extraParameters
  824. forContinuation:YES]];
  825. });
  826. return YES;
  827. }
  828. #pragma mark - Helpers
  829. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  830. if (errorString == nil) {
  831. errorString = @"Unknown error";
  832. }
  833. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  834. return [NSError errorWithDomain:kGIDSignInErrorDomain
  835. code:code
  836. userInfo:errorDict];
  837. }
  838. + (BOOL)isOperatingSystemAtLeast9 {
  839. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  840. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  841. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  842. }
  843. // Asserts the parameters being valid.
  844. - (void)assertValidParameters {
  845. if (![_currentOptions.configuration.clientID length]) {
  846. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  847. [NSException raise:NSInvalidArgumentException
  848. format:@"You must specify |clientID| in |GIDConfiguration|"];
  849. }
  850. }
  851. // Assert that the presenting view controller has been set.
  852. - (void)assertValidPresentingViewController {
  853. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  854. if (!_currentOptions.presentingViewController)
  855. #elif TARGET_OS_OSX
  856. if (!_currentOptions.presentingWindow)
  857. #endif // TARGET_OS_OSX
  858. {
  859. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  860. [NSException raise:NSInvalidArgumentException
  861. format:@"|presentingViewController| must be set."];
  862. }
  863. }
  864. // Checks whether or not this is the first time the app runs.
  865. - (BOOL)isFreshInstall {
  866. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  867. if ([defaults boolForKey:kAppHasRunBeforeKey]) {
  868. return NO;
  869. }
  870. [defaults setBool:YES forKey:kAppHasRunBeforeKey];
  871. return YES;
  872. }
  873. - (void)removeAllKeychainEntries {
  874. [_keychainStore removeAuthSessionWithError:nil];
  875. }
  876. - (BOOL)saveAuthState:(OIDAuthState *)authState {
  877. GTMAuthSession *authorization = [[GTMAuthSession alloc] initWithAuthState:authState];
  878. NSError *error;
  879. [_keychainStore saveAuthSession:authorization error:&error];
  880. return error == nil;
  881. }
  882. - (OIDAuthState *)loadAuthState {
  883. GTMAuthSession *authorization = [_keychainStore retrieveAuthSessionWithError:nil];
  884. return authorization.authState;
  885. }
  886. // Generates user profile from OIDIDToken.
  887. - (GIDProfileData *)profileDataWithIDToken:(OIDIDToken *)idToken {
  888. if (!idToken ||
  889. !idToken.claims[kBasicProfilePictureKey] ||
  890. !idToken.claims[kBasicProfileNameKey] ||
  891. !idToken.claims[kBasicProfileGivenNameKey] ||
  892. !idToken.claims[kBasicProfileFamilyNameKey]) {
  893. return nil;
  894. }
  895. return [[GIDProfileData alloc]
  896. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  897. name:idToken.claims[kBasicProfileNameKey]
  898. givenName:idToken.claims[kBasicProfileGivenNameKey]
  899. familyName:idToken.claims[kBasicProfileFamilyNameKey]
  900. imageURL:[NSURL URLWithString:idToken.claims[kBasicProfilePictureKey]]];
  901. }
  902. // Try to retrieve a configuration value from an |NSBundle|'s Info.plist for a given key.
  903. + (nullable NSString *)configValueFromBundle:(NSBundle *)bundle forKey:(NSString *)key {
  904. NSString *value;
  905. id configValue = [bundle objectForInfoDictionaryKey:key];
  906. if ([configValue isKindOfClass:[NSString class]]) {
  907. value = configValue;
  908. }
  909. return value;
  910. }
  911. // Try to generate a |GIDConfiguration| from an |NSBundle|'s Info.plist.
  912. + (nullable GIDConfiguration *)configurationFromBundle:(NSBundle *)bundle {
  913. GIDConfiguration *configuration;
  914. // Retrieve any valid config parameters from the bundle's Info.plist.
  915. NSString *clientID = [GIDSignIn configValueFromBundle:bundle forKey:kConfigClientIDKey];
  916. NSString *serverClientID = [GIDSignIn configValueFromBundle:bundle
  917. forKey:kConfigServerClientIDKey];
  918. NSString *hostedDomain = [GIDSignIn configValueFromBundle:bundle forKey:kConfigHostedDomainKey];
  919. NSString *openIDRealm = [GIDSignIn configValueFromBundle:bundle forKey:kConfigOpenIDRealmKey];
  920. // If we have at least a client ID, try to construct a configuration.
  921. if (clientID) {
  922. configuration = [[GIDConfiguration alloc] initWithClientID:clientID
  923. serverClientID:serverClientID
  924. hostedDomain:hostedDomain
  925. openIDRealm:openIDRealm];
  926. }
  927. return configuration;
  928. }
  929. @end
  930. NS_ASSUME_NONNULL_END