GIDSignIn.m 34 KB

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