GIDSignIn.m 32 KB

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