GIDSignIn.m 32 KB

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