GIDSignIn.m 43 KB

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