GIDSignIn.m 42 KB

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