GIDSignIn.m 35 KB

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