GIDSignIn.m 34 KB

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