GIDSignIn.m 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  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. #import "GoogleSignIn/Sources/GIDAuthStateMigration.h"
  26. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  27. #import "GoogleSignIn/Sources/GIDAuthentication_Private.h"
  28. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  29. #import "GoogleSignIn/Sources/GIDProfileData_Private.h"
  30. #ifdef SWIFT_PACKAGE
  31. @import AppAuth;
  32. @import GTMAppAuth;
  33. @import GTMSessionFetcherCore;
  34. #else
  35. #import <AppAuth/OIDAuthState.h>
  36. #import <AppAuth/OIDAuthorizationRequest.h>
  37. #import <AppAuth/OIDAuthorizationResponse.h>
  38. #import <AppAuth/OIDAuthorizationService.h>
  39. #import <AppAuth/OIDError.h>
  40. #import <AppAuth/OIDExternalUserAgentSession.h>
  41. #import <AppAuth/OIDIDToken.h>
  42. #import <AppAuth/OIDResponseTypes.h>
  43. #import <AppAuth/OIDServiceConfiguration.h>
  44. #import <AppAuth/OIDTokenRequest.h>
  45. #import <AppAuth/OIDTokenResponse.h>
  46. #import <AppAuth/OIDURLQueryComponent.h>
  47. #import <AppAuth/OIDAuthorizationService+IOS.h>
  48. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization+Keychain.h>
  49. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization.h>
  50. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  51. #endif
  52. NS_ASSUME_NONNULL_BEGIN
  53. // The name of the query parameter used for logging the restart of auth from EMM callback.
  54. static NSString *const kEMMRestartAuthParameter = @"emmres";
  55. // The URL template for the authorization endpoint.
  56. static NSString *const kAuthorizationURLTemplate = @"https://%@/o/oauth2/v2/auth";
  57. // The URL template for the token endpoint.
  58. static NSString *const kTokenURLTemplate = @"https://%@/token";
  59. // The URL template for the URL to get user info.
  60. static NSString *const kUserInfoURLTemplate = @"https://%@/oauth2/v3/userinfo?access_token=%@";
  61. // The URL template for the URL to revoke the token.
  62. static NSString *const kRevokeTokenURLTemplate = @"https://%@/o/oauth2/revoke?token=%@";
  63. // Expected path in the URL scheme to be handled.
  64. static NSString *const kBrowserCallbackPath = @"/oauth2callback";
  65. // Expected path for EMM callback.
  66. static NSString *const kEMMCallbackPath = @"/emmcallback";
  67. // The EMM support version
  68. static NSString *const kEMMVersion = @"1";
  69. // The error code for Google Identity.
  70. NSErrorDomain const kGIDSignInErrorDomain = @"com.google.GIDSignIn";
  71. // Keychain constants for saving state in the authentication flow.
  72. static NSString *const kGTMAppAuthKeychainName = @"auth";
  73. // Basic profile (Fat ID Token / userinfo endpoint) keys
  74. static NSString *const kBasicProfileEmailKey = @"email";
  75. static NSString *const kBasicProfilePictureKey = @"picture";
  76. static NSString *const kBasicProfileNameKey = @"name";
  77. static NSString *const kBasicProfileGivenNameKey = @"given_name";
  78. static NSString *const kBasicProfileFamilyNameKey = @"family_name";
  79. // Parameters in the callback URL coming back from browser.
  80. static NSString *const kAuthorizationCodeKeyName = @"code";
  81. static NSString *const kOAuth2ErrorKeyName = @"error";
  82. static NSString *const kOAuth2AccessDenied = @"access_denied";
  83. static NSString *const kEMMPasscodeInfoRequiredKeyName = @"emm_passcode_info_required";
  84. // Error string for unavailable keychain.
  85. static NSString *const kKeychainError = @"keychain error";
  86. // Error string for user cancelations.
  87. static NSString *const kUserCanceledError = @"The user canceled the sign-in flow.";
  88. // User preference key to detect fresh install of the app.
  89. static NSString *const kAppHasRunBeforeKey = @"GID_AppHasRunBefore";
  90. // Maximum retry interval in seconds for the fetcher.
  91. static const NSTimeInterval kFetcherMaxRetryInterval = 15.0;
  92. // The delay before the new sign-in flow can be presented after the existing one is cancelled.
  93. static const NSTimeInterval kPresentationDelayAfterCancel = 1.0;
  94. // Extra parameters for the token exchange endpoint.
  95. static NSString *const kAudienceParameter = @"audience";
  96. // See b/11669751 .
  97. static NSString *const kOpenIDRealmParameter = @"openid.realm";
  98. // Minimum time to expiration for a restored access token.
  99. static const NSTimeInterval kMinimumRestoredAccessTokenTimeToExpire = 600.0;
  100. // The callback queue used for authentication flow.
  101. @interface GIDAuthFlow : GIDCallbackQueue
  102. @property(nonatomic, strong, nullable) OIDAuthState *authState;
  103. @property(nonatomic, strong, nullable) NSError *error;
  104. @property(nonatomic, copy, nullable) NSString *emmSupport;
  105. @property(nonatomic, nullable) GIDProfileData *profileData;
  106. @end
  107. @implementation GIDAuthFlow
  108. @end
  109. @implementation GIDSignIn {
  110. // This value is used when sign-in flows are resumed via the handling of a URL. Its value is
  111. // set when a sign-in flow is begun via |signInWithOptions:| when the options passed don't
  112. // represent a sign in continuation.
  113. GIDSignInInternalOptions *_currentOptions;
  114. // AppAuth configuration object.
  115. OIDServiceConfiguration *_appAuthConfiguration;
  116. // AppAuth external user-agent session state.
  117. id<OIDExternalUserAgentSession> _currentAuthorizationFlow;
  118. // Flag to indicate that the auth flow is restarting.
  119. BOOL _restarting;
  120. }
  121. #pragma mark - Public methods
  122. - (BOOL)handleURL:(NSURL *)url {
  123. // Check if the callback path matches the expected one for a URL from Safari/Chrome/SafariVC.
  124. if ([url.path isEqual:kBrowserCallbackPath]) {
  125. if ([_currentAuthorizationFlow resumeExternalUserAgentFlowWithURL:url]) {
  126. _currentAuthorizationFlow = nil;
  127. return YES;
  128. }
  129. return NO;
  130. }
  131. // Check if the callback path matches the expected one for a URL from Google Device Policy app.
  132. if ([url.path isEqual:kEMMCallbackPath]) {
  133. return [self handleDevicePolicyAppURL:url];
  134. }
  135. return NO;
  136. }
  137. - (BOOL)hasPreviousSignIn {
  138. if ([_currentUser.authentication.authState isAuthorized]) {
  139. return YES;
  140. }
  141. OIDAuthState *authState = [self loadAuthState];
  142. return [authState isAuthorized];
  143. }
  144. - (void)restorePreviousSignInWithCallback:(nullable GIDSignInCallback)callback {
  145. [self signInWithOptions:[GIDSignInInternalOptions silentOptionsWithCallback:callback]];
  146. }
  147. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  148. presentingViewController:(UIViewController *)presentingViewController
  149. hint:(nullable NSString *)hint
  150. callback:(nullable GIDSignInCallback)callback {
  151. GIDSignInInternalOptions *options =
  152. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  153. presentingViewController:presentingViewController
  154. loginHint:hint
  155. callback:callback];
  156. [self signInWithOptions:options];
  157. }
  158. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  159. presentingViewController:(UIViewController *)presentingViewController
  160. callback:(nullable GIDSignInCallback)callback {
  161. [self signInWithConfiguration:configuration
  162. presentingViewController:presentingViewController
  163. hint:nil
  164. callback:callback];
  165. }
  166. - (void)addScopes:(NSArray<NSString *> *)scopes
  167. presentingViewController:(UIViewController *)presentingViewController
  168. callback:(nullable GIDSignInCallback)callback {
  169. // A currentUser must be available in order to complete this flow.
  170. if (!self.currentUser) {
  171. // No currentUser is set, notify callback of failure.
  172. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  173. code:kGIDSignInErrorCodeNoCurrentUser
  174. userInfo:nil];
  175. if (callback) {
  176. dispatch_async(dispatch_get_main_queue(), ^{
  177. callback(nil, error);
  178. });
  179. }
  180. return;
  181. }
  182. GIDConfiguration *configuration =
  183. [[GIDConfiguration alloc] initWithClientID:self.currentUser.authentication.clientID
  184. serverClientID:self.currentUser.serverClientID
  185. hostedDomain:self.currentUser.hostedDomain
  186. openIDRealm:self.currentUser.openIDRealm];
  187. GIDSignInInternalOptions *options =
  188. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  189. presentingViewController:presentingViewController
  190. loginHint:self.currentUser.profile.email
  191. callback:callback];
  192. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  193. NSMutableSet<NSString *> *grantedScopes =
  194. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  195. // Check to see if all requested scopes have already been granted.
  196. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  197. // All requested scopes have already been granted, notify callback of failure.
  198. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  199. code:kGIDSignInErrorCodeScopesAlreadyGranted
  200. userInfo:nil];
  201. if (callback) {
  202. dispatch_async(dispatch_get_main_queue(), ^{
  203. callback(nil, error);
  204. });
  205. }
  206. return;
  207. }
  208. // Use the union of granted and requested scopes.
  209. [grantedScopes unionSet:requestedScopes];
  210. options.scopes = [grantedScopes allObjects];
  211. [self signInWithOptions:options];
  212. }
  213. - (void)signOut {
  214. // Clear the current user if there is one.
  215. if (_currentUser) {
  216. [self willChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  217. _currentUser = nil;
  218. [self didChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  219. }
  220. // Remove all state from the keychain.
  221. [self removeAllKeychainEntries];
  222. }
  223. - (void)disconnectWithCallback:(nullable GIDDisconnectCallback)callback {
  224. GIDGoogleUser *user = _currentUser;
  225. OIDAuthState *authState = user.authentication.authState;
  226. if (!authState) {
  227. // Even the user is not signed in right now, we still need to remove any token saved in the
  228. // keychain.
  229. authState = [self loadAuthState];
  230. }
  231. // Either access or refresh token would work, but we won't have access token if the auth is
  232. // retrieved from keychain.
  233. NSString *token = authState.lastTokenResponse.accessToken;
  234. if (!token) {
  235. token = authState.lastTokenResponse.refreshToken;
  236. }
  237. if (!token) {
  238. [self signOut];
  239. // Nothing to do here, consider the operation successful.
  240. if (callback) {
  241. dispatch_async(dispatch_get_main_queue(), ^{
  242. callback(nil);
  243. });
  244. }
  245. return;
  246. }
  247. NSString *revokeURLString = [NSString stringWithFormat:kRevokeTokenURLTemplate,
  248. [GIDSignInPreferences googleAuthorizationServer], token];
  249. // Append logging parameter
  250. revokeURLString = [NSString stringWithFormat:@"%@&%@=%@",
  251. revokeURLString,
  252. kSDKVersionLoggingParameter,
  253. GIDVersion()];
  254. NSURL *revokeURL = [NSURL URLWithString:revokeURLString];
  255. [self startFetchURL:revokeURL
  256. fromAuthState:authState
  257. withComment:@"GIDSignIn: revoke tokens"
  258. withCompletionHandler:^(NSData *data, NSError *error) {
  259. // Revoking an already revoked token seems always successful, which helps us here.
  260. if (!error) {
  261. [self signOut];
  262. }
  263. if (callback) {
  264. dispatch_async(dispatch_get_main_queue(), ^{
  265. callback(error);
  266. });
  267. }
  268. }];
  269. }
  270. #pragma mark - Custom getters and setters
  271. + (GIDSignIn *)sharedInstance {
  272. static dispatch_once_t once;
  273. static GIDSignIn *sharedInstance;
  274. dispatch_once(&once, ^{
  275. sharedInstance = [[self alloc] initPrivate];
  276. });
  277. return sharedInstance;
  278. }
  279. #pragma mark - Private methods
  280. - (id)initPrivate {
  281. self = [super init];
  282. if (self) {
  283. // Check to see if the 3P app is being run for the first time after a fresh install.
  284. BOOL isFreshInstall = [self isFreshInstall];
  285. // If this is a fresh install, ensure that any pre-existing keychain data is purged.
  286. if (isFreshInstall) {
  287. [self removeAllKeychainEntries];
  288. }
  289. NSString *authorizationEnpointURL = [NSString stringWithFormat:kAuthorizationURLTemplate,
  290. [GIDSignInPreferences googleAuthorizationServer]];
  291. NSString *tokenEndpointURL = [NSString stringWithFormat:kTokenURLTemplate,
  292. [GIDSignInPreferences googleTokenServer]];
  293. _appAuthConfiguration = [[OIDServiceConfiguration alloc]
  294. initWithAuthorizationEndpoint:[NSURL URLWithString:authorizationEnpointURL]
  295. tokenEndpoint:[NSURL URLWithString:tokenEndpointURL]];
  296. // Perform migration of auth state from old versions of the SDK if needed.
  297. [GIDAuthStateMigration migrateIfNeededWithTokenURL:_appAuthConfiguration.tokenEndpoint
  298. callbackPath:kBrowserCallbackPath
  299. keychainName:kGTMAppAuthKeychainName
  300. isFreshInstall:isFreshInstall];
  301. }
  302. return self;
  303. }
  304. // Does sanity check for parameters and then authenticates if necessary.
  305. - (void)signInWithOptions:(GIDSignInInternalOptions *)options {
  306. // Options for continuation are not the options we want to cache. The purpose of caching the
  307. // options in the first place is to provide continuation flows with a starting place from which to
  308. // derive suitable options for the continuation!
  309. if (!options.continuation) {
  310. _currentOptions = options;
  311. }
  312. if (options.interactive) {
  313. // Explicitly throw exception for missing client ID here. This must come before
  314. // scheme check because schemes rely on reverse client IDs.
  315. [self assertValidParameters];
  316. [self assertValidPresentingViewController];
  317. // If the application does not support the required URL schemes tell the developer so.
  318. GIDSignInCallbackSchemes *schemes =
  319. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  320. NSArray<NSString *> *unsupportedSchemes = [schemes unsupportedSchemes];
  321. if (unsupportedSchemes.count != 0) {
  322. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  323. [NSException raise:NSInvalidArgumentException
  324. format:@"Your app is missing support for the following URL schemes: %@",
  325. [unsupportedSchemes componentsJoinedByString:@", "]];
  326. }
  327. }
  328. // If this is a non-interactive flow, use cached authentication if possible.
  329. if (!options.interactive && _currentUser.authentication) {
  330. [_currentUser.authentication doWithFreshTokens:^(GIDAuthentication *unused, NSError *error) {
  331. if (error) {
  332. [self authenticateWithOptions:options];
  333. } else {
  334. if (options.callback) {
  335. dispatch_async(dispatch_get_main_queue(), ^{
  336. options.callback(_currentUser, nil);
  337. _currentOptions = nil;
  338. });
  339. }
  340. }
  341. }];
  342. } else {
  343. [self authenticateWithOptions:options];
  344. }
  345. }
  346. - (nullable GIDGoogleUser *)restoredGoogleUserFromPreviousSignIn {
  347. OIDAuthState *authState = [self loadAuthState];
  348. if (!authState) {
  349. return nil;
  350. }
  351. return [[GIDGoogleUser alloc] initWithAuthState:authState
  352. profileData:nil];
  353. }
  354. # pragma mark - Authentication flow
  355. - (void)authenticateInteractivelyWithOptions:(GIDSignInInternalOptions *)options {
  356. GIDSignInCallbackSchemes *schemes =
  357. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  358. NSURL *redirectURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@:%@",
  359. [schemes clientIdentifierScheme],
  360. kBrowserCallbackPath]];
  361. NSString *emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  362. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  363. if (options.configuration.serverClientID) {
  364. additionalParameters[kAudienceParameter] = options.configuration.serverClientID;
  365. }
  366. if (options.loginHint) {
  367. additionalParameters[@"login_hint"] = options.loginHint;
  368. }
  369. if (options.configuration.hostedDomain) {
  370. additionalParameters[@"hd"] = options.configuration.hostedDomain;
  371. }
  372. [additionalParameters addEntriesFromDictionary:
  373. [GIDAuthentication parametersWithParameters:options.extraParams
  374. emmSupport:emmSupport
  375. isPasscodeInfoRequired:NO]];
  376. OIDAuthorizationRequest *request =
  377. [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  378. clientId:options.configuration.clientID
  379. scopes:options.scopes
  380. redirectURL:redirectURL
  381. responseType:OIDResponseTypeCode
  382. additionalParameters:additionalParameters];
  383. _currentAuthorizationFlow = [OIDAuthorizationService
  384. presentAuthorizationRequest:request
  385. presentingViewController:options.presentingViewController
  386. callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  387. NSError *_Nullable error) {
  388. if (_restarting) {
  389. // The auth flow is restarting, so the work here would be performed in the next round.
  390. _restarting = NO;
  391. return;
  392. }
  393. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  394. authFlow.emmSupport = emmSupport;
  395. if (authorizationResponse) {
  396. if (authorizationResponse.authorizationCode.length) {
  397. authFlow.authState = [[OIDAuthState alloc]
  398. initWithAuthorizationResponse:authorizationResponse];
  399. // perform auth code exchange
  400. [self maybeFetchToken:authFlow fallback:nil];
  401. } else {
  402. // There was a failure, convert to appropriate error code.
  403. NSString *errorString;
  404. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  405. NSDictionary<NSString *, NSObject *> *params = authorizationResponse.additionalParameters;
  406. if (authFlow.emmSupport) {
  407. [authFlow wait];
  408. BOOL isEMMError = [[GIDEMMErrorHandler sharedInstance]
  409. handleErrorFromResponse:params
  410. completion:^{
  411. [authFlow next];
  412. }];
  413. if (isEMMError) {
  414. errorCode = kGIDSignInErrorCodeEMM;
  415. }
  416. }
  417. errorString = (NSString *)params[kOAuth2ErrorKeyName];
  418. if ([errorString isEqualToString:kOAuth2AccessDenied]) {
  419. errorCode = kGIDSignInErrorCodeCanceled;
  420. }
  421. authFlow.error = [self errorWithString:errorString code:errorCode];
  422. }
  423. } else {
  424. NSString *errorString = [error localizedDescription];
  425. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  426. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow) {
  427. // The user has canceled the flow at the iOS modal dialog.
  428. errorString = kUserCanceledError;
  429. errorCode = kGIDSignInErrorCodeCanceled;
  430. }
  431. authFlow.error = [self errorWithString:errorString code:errorCode];
  432. }
  433. [self addDecodeIdTokenCallback:authFlow];
  434. [self addSaveAuthCallback:authFlow];
  435. [self addCompletionCallback:authFlow];
  436. }];
  437. }
  438. // Perform authentication with the provided options.
  439. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options {
  440. // If this is an interactive flow, we're not going to try to restore any saved auth state.
  441. if (options.interactive) {
  442. [self authenticateInteractivelyWithOptions:options];
  443. return;
  444. }
  445. // Try retrieving an authorization object from the keychain.
  446. OIDAuthState *authState = [self loadAuthState];
  447. if (![authState isAuthorized]) {
  448. // No valid auth in keychain, per documentation/spec, notify callback of failure.
  449. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  450. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  451. userInfo:nil];
  452. if (options.callback) {
  453. dispatch_async(dispatch_get_main_queue(), ^{
  454. options.callback(nil, error);
  455. _currentOptions = nil;
  456. });
  457. }
  458. return;
  459. }
  460. // Complete the auth flow using saved auth in keychain.
  461. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  462. authFlow.authState = authState;
  463. [self maybeFetchToken:authFlow fallback:options.interactive ? ^() {
  464. [self authenticateInteractivelyWithOptions:options];
  465. } : nil];
  466. [self addDecodeIdTokenCallback:authFlow];
  467. [self addSaveAuthCallback:authFlow];
  468. [self addCompletionCallback:authFlow];
  469. }
  470. // Fetches the access token if necessary as part of the auth flow. If |fallback|
  471. // is provided, call it instead of continuing the auth flow in case of error.
  472. - (void)maybeFetchToken:(GIDAuthFlow *)authFlow fallback:(nullable void (^)(void))fallback {
  473. OIDAuthState *authState = authFlow.authState;
  474. // Do nothing if we have an auth flow error or a restored access token that isn't near expiration.
  475. if (authFlow.error ||
  476. (authState.lastTokenResponse.accessToken &&
  477. [authState.lastTokenResponse.accessTokenExpirationDate timeIntervalSinceNow] >
  478. kMinimumRestoredAccessTokenTimeToExpire)) {
  479. return;
  480. }
  481. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  482. if (_currentOptions.configuration.serverClientID) {
  483. additionalParameters[kAudienceParameter] = _currentOptions.configuration.serverClientID;
  484. }
  485. if (_currentOptions.configuration.openIDRealm) {
  486. additionalParameters[kOpenIDRealmParameter] = _currentOptions.configuration.openIDRealm;
  487. }
  488. NSDictionary<NSString *, NSObject *> *params =
  489. authState.lastAuthorizationResponse.additionalParameters;
  490. NSString *passcodeInfoRequired = (NSString *)params[kEMMPasscodeInfoRequiredKeyName];
  491. [additionalParameters addEntriesFromDictionary:
  492. [GIDAuthentication parametersWithParameters:@{}
  493. emmSupport:authFlow.emmSupport
  494. isPasscodeInfoRequired:passcodeInfoRequired.length > 0]];
  495. OIDTokenRequest *tokenRequest;
  496. if (!authState.lastTokenResponse.accessToken &&
  497. authState.lastAuthorizationResponse.authorizationCode) {
  498. tokenRequest = [authState.lastAuthorizationResponse
  499. tokenExchangeRequestWithAdditionalParameters:additionalParameters];
  500. } else {
  501. [additionalParameters
  502. addEntriesFromDictionary:authState.lastTokenResponse.request.additionalParameters];
  503. tokenRequest = [authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  504. }
  505. [authFlow wait];
  506. [OIDAuthorizationService
  507. performTokenRequest:tokenRequest
  508. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  509. NSError *_Nullable error) {
  510. [authState updateWithTokenResponse:tokenResponse error:error];
  511. authFlow.error = error;
  512. if (!tokenResponse.accessToken || error) {
  513. if (fallback) {
  514. [authFlow reset];
  515. fallback();
  516. return;
  517. }
  518. }
  519. if (authFlow.emmSupport) {
  520. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *error) {
  521. authFlow.error = error;
  522. [authFlow next];
  523. }];
  524. } else {
  525. [authFlow next];
  526. }
  527. }];
  528. }
  529. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  530. - (void)addSaveAuthCallback:(GIDAuthFlow *)authFlow {
  531. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  532. [authFlow addCallback:^() {
  533. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  534. OIDAuthState *authState = handlerAuthFlow.authState;
  535. if (authState && !handlerAuthFlow.error) {
  536. if (![self saveAuthState:authState]) {
  537. handlerAuthFlow.error = [self errorWithString:kKeychainError
  538. code:kGIDSignInErrorCodeKeychain];
  539. return;
  540. }
  541. [self willChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  542. _currentUser = [[GIDGoogleUser alloc] initWithAuthState:authState
  543. profileData:handlerAuthFlow.profileData];
  544. [self didChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  545. }
  546. }];
  547. }
  548. // Adds a callback to the auth flow to extract user data from the ID token where available and
  549. // make a userinfo request if necessary.
  550. - (void)addDecodeIdTokenCallback:(GIDAuthFlow *)authFlow {
  551. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  552. [authFlow addCallback:^() {
  553. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  554. OIDAuthState *authState = handlerAuthFlow.authState;
  555. if (!authState || handlerAuthFlow.error) {
  556. return;
  557. }
  558. OIDIDToken *idToken =
  559. [[OIDIDToken alloc] initWithIDTokenString:authState.lastTokenResponse.idToken];
  560. if (idToken) {
  561. // If the picture and name fields are present in the ID token, use them, otherwise make
  562. // a userinfo request to fetch them.
  563. if (idToken.claims[kBasicProfilePictureKey] &&
  564. idToken.claims[kBasicProfileNameKey] &&
  565. idToken.claims[kBasicProfileGivenNameKey] &&
  566. idToken.claims[kBasicProfileFamilyNameKey]) {
  567. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  568. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  569. name:idToken.claims[kBasicProfileNameKey]
  570. givenName:idToken.claims[kBasicProfileGivenNameKey]
  571. familyName:idToken.claims[kBasicProfileFamilyNameKey]
  572. imageURL:[NSURL URLWithString:idToken.claims[kBasicProfilePictureKey]]];
  573. } else {
  574. [handlerAuthFlow wait];
  575. NSURL *infoURL = [NSURL URLWithString:
  576. [NSString stringWithFormat:kUserInfoURLTemplate,
  577. [GIDSignInPreferences googleUserInfoServer],
  578. authState.lastTokenResponse.accessToken]];
  579. [self startFetchURL:infoURL
  580. fromAuthState:authState
  581. withComment:@"GIDSignIn: fetch basic profile info"
  582. withCompletionHandler:^(NSData *data, NSError *error) {
  583. if (data && !error) {
  584. NSError *jsonDeserializationError;
  585. NSDictionary<NSString *, NSString *> *profileDict =
  586. [NSJSONSerialization JSONObjectWithData:data
  587. options:NSJSONReadingMutableContainers
  588. error:&jsonDeserializationError];
  589. if (profileDict) {
  590. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  591. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  592. name:profileDict[kBasicProfileNameKey]
  593. givenName:profileDict[kBasicProfileGivenNameKey]
  594. familyName:profileDict[kBasicProfileFamilyNameKey]
  595. imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
  596. }
  597. }
  598. if (error) {
  599. handlerAuthFlow.error = error;
  600. }
  601. [handlerAuthFlow next];
  602. }];
  603. }
  604. }
  605. }];
  606. }
  607. // Adds a callback to the auth flow to complete the flow by calling the sign-in callback.
  608. - (void)addCompletionCallback:(GIDAuthFlow *)authFlow {
  609. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  610. [authFlow addCallback:^() {
  611. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  612. if (_currentOptions.callback) {
  613. dispatch_async(dispatch_get_main_queue(), ^{
  614. _currentOptions.callback(_currentUser, handlerAuthFlow.error);
  615. _currentOptions = nil;
  616. });
  617. }
  618. }];
  619. }
  620. - (void)startFetchURL:(NSURL *)URL
  621. fromAuthState:(OIDAuthState *)authState
  622. withComment:(NSString *)comment
  623. withCompletionHandler:(void (^)(NSData *, NSError *))handler {
  624. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  625. GTMSessionFetcher *fetcher;
  626. GTMAppAuthFetcherAuthorization *authorization =
  627. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  628. id<GTMSessionFetcherServiceProtocol> fetcherService = authorization.fetcherService;
  629. if (fetcherService) {
  630. fetcher = [fetcherService fetcherWithRequest:request];
  631. } else {
  632. fetcher = [GTMSessionFetcher fetcherWithRequest:request];
  633. }
  634. fetcher.retryEnabled = YES;
  635. fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
  636. fetcher.comment = comment;
  637. [fetcher beginFetchWithCompletionHandler:handler];
  638. }
  639. // Parse incoming URL from the Google Device Policy app.
  640. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  641. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  642. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  643. NSObject<NSCopying> *actionParam = params[@"action"];
  644. NSString *actionString =
  645. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  646. if (![@"restart_auth" isEqualToString:actionString]) {
  647. return NO;
  648. }
  649. if (!_currentOptions.presentingViewController) {
  650. return NO;
  651. }
  652. if (!_currentAuthorizationFlow) {
  653. return NO;
  654. }
  655. _restarting = YES;
  656. [_currentAuthorizationFlow cancel];
  657. _currentAuthorizationFlow = nil;
  658. _restarting = NO;
  659. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  660. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  661. // so we need to wait until the previous presentation is completely gone to ensure the right
  662. // anchor window is used here.
  663. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  664. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  665. dispatch_get_main_queue(), ^{
  666. [self signInWithOptions:[_currentOptions optionsWithExtraParameters:extraParameters
  667. forContinuation:YES]];
  668. });
  669. return YES;
  670. }
  671. #pragma mark - Key-Value Observing
  672. // Override |NSObject(NSKeyValueObservingCustomization)| method in order to provide custom KVO
  673. // notifications for |clientID| and |currentUser| properties.
  674. + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
  675. if ([key isEqual:NSStringFromSelector(@selector(clientID))] ||
  676. [key isEqual:NSStringFromSelector(@selector(currentUser))]) {
  677. return NO;
  678. }
  679. return [super automaticallyNotifiesObserversForKey:key];
  680. }
  681. #pragma mark - Helpers
  682. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  683. if (errorString == nil) {
  684. errorString = @"Unknown error";
  685. }
  686. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  687. return [NSError errorWithDomain:kGIDSignInErrorDomain
  688. code:code
  689. userInfo:errorDict];
  690. }
  691. + (BOOL)isOperatingSystemAtLeast9 {
  692. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  693. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  694. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  695. }
  696. // Asserts the parameters being valid.
  697. - (void)assertValidParameters {
  698. if (![_currentOptions.configuration.clientID length]) {
  699. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  700. [NSException raise:NSInvalidArgumentException
  701. format:@"You must specify |clientID| in |GIDConfiguration|"];
  702. }
  703. }
  704. // Assert that the presenting view controller has been set.
  705. - (void)assertValidPresentingViewController {
  706. if (!_currentOptions.presentingViewController) {
  707. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  708. [NSException raise:NSInvalidArgumentException
  709. format:@"|presentingViewController| must be set."];
  710. }
  711. }
  712. // Checks whether or not this is the first time the app runs.
  713. - (BOOL)isFreshInstall {
  714. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  715. if ([defaults boolForKey:kAppHasRunBeforeKey]) {
  716. return NO;
  717. }
  718. [defaults setBool:YES forKey:kAppHasRunBeforeKey];
  719. return YES;
  720. }
  721. - (void)removeAllKeychainEntries {
  722. [GTMAppAuthFetcherAuthorization removeAuthorizationFromKeychainForName:kGTMAppAuthKeychainName];
  723. }
  724. - (BOOL)saveAuthState:(OIDAuthState *)authState {
  725. GTMAppAuthFetcherAuthorization *authorization =
  726. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  727. return [GTMAppAuthFetcherAuthorization saveAuthorization:authorization
  728. toKeychainForName:kGTMAppAuthKeychainName];
  729. }
  730. - (OIDAuthState *)loadAuthState {
  731. GTMAppAuthFetcherAuthorization *authorization =
  732. [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:kGTMAppAuthKeychainName];
  733. return authorization.authState;
  734. }
  735. @end
  736. NS_ASSUME_NONNULL_END