GIDSignIn.m 31 KB

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