GIDSignIn.m 32 KB

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