GIDSignIn.m 42 KB

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