GIDSignIn.m 34 KB

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