GIDSignIn.m 43 KB

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