GIDSignIn.m 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. // Copyright 2023 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/GIDConfiguration.h"
  17. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDGoogleUser.h"
  18. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDProfileData.h"
  19. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDSignInResult.h"
  20. #import "GoogleSignIn/Sources/GIDAuthorizationFlowProcessor/API/GIDAuthorizationFlowProcessor.h"
  21. #import "GoogleSignIn/Sources/GIDAuthorizationFlowProcessor/Implementations/GIDAuthorizationFlowProcessor.h"
  22. #import "GoogleSignIn/Sources/GIDAuthorizationUtil.h"
  23. #import "GoogleSignIn/Sources/GIDHTTPFetcher/API/GIDHTTPFetcher.h"
  24. #import "GoogleSignIn/Sources/GIDHTTPFetcher/Implementations/GIDHTTPFetcher.h"
  25. #import "GoogleSignIn/Sources/GIDEMMSupport.h"
  26. #import "GoogleSignIn/Sources/GIDKeychainHandler/API/GIDKeychainHandler.h"
  27. #import "GoogleSignIn/Sources/GIDKeychainHandler/Implementations/GIDKeychainHandler.h"
  28. #import "GoogleSignIn/Sources/GIDProfileDataFetcher/API/GIDProfileDataFetcher.h"
  29. #import "GoogleSignIn/Sources/GIDProfileDataFetcher/Implementations/GIDProfileDataFetcher.h"
  30. #import "GoogleSignIn/Sources/GIDSignInInternalOptions.h"
  31. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  32. #import "GoogleSignIn/Sources/GIDCallbackQueue.h"
  33. #import "GoogleSignIn/Sources/GIDScopes.h"
  34. #import "GoogleSignIn/Sources/GIDSignInCallbackSchemes.h"
  35. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  36. #import "GoogleSignIn/Sources/GIDAuthStateMigration.h"
  37. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  38. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  39. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  40. #import "GoogleSignIn/Sources/GIDProfileData_Private.h"
  41. #import "GoogleSignIn/Sources/GIDSignInResult_Private.h"
  42. #ifdef SWIFT_PACKAGE
  43. @import AppAuth;
  44. @import GTMAppAuth;
  45. @import GTMSessionFetcherCore;
  46. #else
  47. #import <AppAuth/OIDAuthState.h>
  48. #import <AppAuth/OIDAuthorizationRequest.h>
  49. #import <AppAuth/OIDAuthorizationResponse.h>
  50. #import <AppAuth/OIDAuthorizationService.h>
  51. #import <AppAuth/OIDError.h>
  52. #import <AppAuth/OIDExternalUserAgentSession.h>
  53. #import <AppAuth/OIDIDToken.h>
  54. #import <AppAuth/OIDResponseTypes.h>
  55. #import <AppAuth/OIDServiceConfiguration.h>
  56. #import <AppAuth/OIDTokenRequest.h>
  57. #import <AppAuth/OIDTokenResponse.h>
  58. #import <AppAuth/OIDURLQueryComponent.h>
  59. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization+Keychain.h>
  60. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization.h>
  61. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  62. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  63. #import <AppAuth/OIDAuthorizationService+IOS.h>
  64. #elif TARGET_OS_OSX
  65. #import <AppAuth/OIDAuthorizationService+Mac.h>
  66. #endif
  67. #endif
  68. NS_ASSUME_NONNULL_BEGIN
  69. // The EMM support version
  70. NSString *const kEMMVersion = @"1";
  71. // The name of the query parameter used for logging the restart of auth from EMM callback.
  72. static NSString *const kEMMRestartAuthParameter = @"emmres";
  73. // The URL template for the URL to revoke the token.
  74. static NSString *const kRevokeTokenURLTemplate = @"https://%@/o/oauth2/revoke";
  75. // Expected path for EMM callback.
  76. static NSString *const kEMMCallbackPath = @"/emmcallback";
  77. // The error code for Google Identity.
  78. NSErrorDomain const kGIDSignInErrorDomain = @"com.google.GIDSignIn";
  79. // Keychain constants for saving state in the authentication flow.
  80. static NSString *const kGTMAppAuthKeychainName = @"auth";
  81. // Parameters in the callback URL coming back from browser.
  82. static NSString *const kAuthorizationCodeKeyName = @"code";
  83. static NSString *const kOAuth2ErrorKeyName = @"error";
  84. static NSString *const kOAuth2AccessDenied = @"access_denied";
  85. static NSString *const kEMMPasscodeInfoRequiredKeyName = @"emm_passcode_info_required";
  86. // Error string for unavailable keychain.
  87. static NSString *const kKeychainError = @"keychain error";
  88. // Error string for user cancelations.
  89. static NSString *const kUserCanceledError = @"The user canceled the sign-in flow.";
  90. // User preference key to detect fresh install of the app.
  91. static NSString *const kAppHasRunBeforeKey = @"GID_AppHasRunBefore";
  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. // See b/11669751 .
  95. static NSString *const kOpenIDRealmParameter = @"openid.realm";
  96. // Minimum time to expiration for a restored access token.
  97. static const NSTimeInterval kMinimumRestoredAccessTokenTimeToExpire = 600.0;
  98. // Info.plist config keys
  99. static NSString *const kConfigClientIDKey = @"GIDClientID";
  100. static NSString *const kConfigServerClientIDKey = @"GIDServerClientID";
  101. static NSString *const kConfigHostedDomainKey = @"GIDHostedDomain";
  102. static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
  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. // Flag to indicate that the auth flow is restarting.
  118. BOOL _restarting;
  119. // The class to execute keychain operations.
  120. id<GIDKeychainHandler> _keychainHandler;
  121. // The class to fetch GIDProfileData object.
  122. id<GIDProfileDataFetcher> _profileDataFetcher;
  123. // The class to fetches data from a url end point.
  124. id<GIDHTTPFetcher> _httpFetcher;
  125. // The class to control the authorization flow.
  126. id<GIDAuthorizationFlowProcessor> _authorizationFlowProcessor;
  127. }
  128. #pragma mark - Public methods
  129. // Handles the custom scheme URL opened by SFSafariViewController or the Device Policy App.
  130. //
  131. // For SFSafariViewController invoked via AppAuth, this method is used on iOS 10.
  132. // For the Device Policy App (EMM flow) this method is used on all iOS versions.
  133. - (BOOL)handleURL:(NSURL *)url {
  134. // Check if the callback path matches the expected one for a URL from Safari/Chrome/SafariVC.
  135. if ([url.path isEqual:kBrowserCallbackPath]) {
  136. if ([_authorizationFlowProcessor resumeExternalUserAgentFlowWithURL:url]) {
  137. return YES;
  138. }
  139. return NO;
  140. }
  141. // Check if the callback path matches the expected one for a URL from Google Device Policy app.
  142. if ([url.path isEqual:kEMMCallbackPath]) {
  143. return [self handleDevicePolicyAppURL:url];
  144. }
  145. return NO;
  146. }
  147. - (BOOL)hasPreviousSignIn {
  148. if ([_currentUser.authState isAuthorized]) {
  149. return YES;
  150. }
  151. OIDAuthState *authState = [_keychainHandler loadAuthState];
  152. return [authState isAuthorized];
  153. }
  154. - (void)restorePreviousSignInWithCompletion:(nullable void (^)(GIDGoogleUser *_Nullable user,
  155. NSError *_Nullable error))completion {
  156. [self signInWithOptions:[GIDSignInInternalOptions silentOptionsWithCompletion:
  157. ^(GIDSignInResult *signInResult, NSError *error) {
  158. if (signInResult) {
  159. completion(signInResult.user, nil);
  160. } else {
  161. completion(nil, error);
  162. }
  163. }]];
  164. }
  165. - (BOOL)restorePreviousSignInNoRefresh {
  166. if (_currentUser) {
  167. return YES;
  168. }
  169. // Try retrieving an authorization object from the keychain.
  170. OIDAuthState *authState = [_keychainHandler loadAuthState];
  171. if (!authState) {
  172. return NO;
  173. }
  174. // Restore current user without refreshing the access token.
  175. OIDIDToken *idToken =
  176. [[OIDIDToken alloc] initWithIDTokenString:authState.lastTokenResponse.idToken];
  177. GIDProfileData *profileData = [_profileDataFetcher fetchProfileDataWithIDToken:idToken];
  178. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState profileData:profileData];
  179. self.currentUser = user;
  180. return YES;
  181. }
  182. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  183. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  184. hint:(nullable NSString *)hint
  185. completion:(nullable GIDSignInCompletion)completion {
  186. GIDSignInInternalOptions *options =
  187. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  188. presentingViewController:presentingViewController
  189. loginHint:hint
  190. addScopesFlow:NO
  191. completion:completion];
  192. [self signInWithOptions:options];
  193. }
  194. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  195. hint:(nullable NSString *)hint
  196. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  197. completion:(nullable GIDSignInCompletion)completion {
  198. GIDSignInInternalOptions *options =
  199. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  200. presentingViewController:presentingViewController
  201. loginHint:hint
  202. addScopesFlow:NO
  203. scopes:additionalScopes
  204. completion:completion];
  205. [self signInWithOptions:options];
  206. }
  207. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  208. completion:(nullable GIDSignInCompletion)completion {
  209. [self signInWithPresentingViewController:presentingViewController
  210. hint:nil
  211. completion:completion];
  212. }
  213. - (void)addScopes:(NSArray<NSString *> *)scopes
  214. presentingViewController:(UIViewController *)presentingViewController
  215. completion:(nullable GIDSignInCompletion)completion {
  216. NSError *error;
  217. NSArray<NSString *> *allScopes =
  218. [GIDAuthorizationUtil resolvedScopesFromGrantedScoped:self.currentUser.grantedScopes
  219. withNewScopes:scopes
  220. error:&error];
  221. if (error) {
  222. if (completion) {
  223. dispatch_async(dispatch_get_main_queue(), ^{
  224. completion(nil, error);
  225. });
  226. }
  227. return;
  228. }
  229. GIDConfiguration *configuration = self.currentUser.configuration;
  230. GIDSignInInternalOptions *options =
  231. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  232. presentingViewController:presentingViewController
  233. loginHint:self.currentUser.profile.email
  234. addScopesFlow:YES
  235. completion:completion];
  236. options.scopes = allScopes;
  237. [self signInWithOptions:options];
  238. }
  239. #elif TARGET_OS_OSX
  240. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  241. hint:(nullable NSString *)hint
  242. completion:(nullable GIDSignInCompletion)completion {
  243. GIDSignInInternalOptions *options =
  244. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  245. presentingWindow:presentingWindow
  246. loginHint:hint
  247. addScopesFlow:NO
  248. completion:completion];
  249. [self signInWithOptions:options];
  250. }
  251. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  252. completion:(nullable GIDSignInCompletion)completion {
  253. [self signInWithPresentingWindow:presentingWindow
  254. hint:nil
  255. completion:completion];
  256. }
  257. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  258. hint:(nullable NSString *)hint
  259. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  260. completion:(nullable GIDSignInCompletion)completion {
  261. GIDSignInInternalOptions *options =
  262. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  263. presentingWindow:presentingWindow
  264. loginHint:hint
  265. addScopesFlow:NO
  266. scopes:additionalScopes
  267. completion:completion];
  268. [self signInWithOptions:options];
  269. }
  270. - (void)addScopes:(NSArray<NSString *> *)scopes
  271. presentingWindow:(NSWindow *)presentingWindow
  272. completion:(nullable GIDSignInCompletion)completion {
  273. GIDConfiguration *configuration = self.currentUser.configuration;
  274. GIDSignInInternalOptions *options =
  275. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  276. presentingWindow:presentingWindow
  277. loginHint:self.currentUser.profile.email
  278. addScopesFlow:YES
  279. completion:completion];
  280. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  281. NSMutableSet<NSString *> *grantedScopes =
  282. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  283. // Check to see if all requested scopes have already been granted.
  284. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  285. // All requested scopes have already been granted, notify callback of failure.
  286. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  287. code:kGIDSignInErrorCodeScopesAlreadyGranted
  288. userInfo:nil];
  289. if (completion) {
  290. dispatch_async(dispatch_get_main_queue(), ^{
  291. completion(nil, error);
  292. });
  293. }
  294. return;
  295. }
  296. // Use the union of granted and requested scopes.
  297. [grantedScopes unionSet:requestedScopes];
  298. options.scopes = [grantedScopes allObjects];
  299. [self signInWithOptions:options];
  300. }
  301. #endif // TARGET_OS_OSX
  302. - (void)signOut {
  303. // Clear the current user if there is one.
  304. if (_currentUser) {
  305. self.currentUser = nil;
  306. }
  307. // Remove all state from the keychain.
  308. [_keychainHandler removeAllKeychainEntries];
  309. }
  310. - (void)disconnectWithCompletion:(nullable GIDDisconnectCompletion)completion {
  311. OIDAuthState *authState = _currentUser.authState;
  312. if (!authState) {
  313. // Even the user is not signed in right now, we still need to remove any token saved in the
  314. // keychain.
  315. authState = [_keychainHandler loadAuthState];
  316. }
  317. // Either access or refresh token would work, but we won't have access token if the auth is
  318. // retrieved from keychain.
  319. NSString *token = authState.lastTokenResponse.accessToken;
  320. if (!token) {
  321. token = authState.lastTokenResponse.refreshToken;
  322. }
  323. if (!token) {
  324. [self signOut];
  325. // Nothing to do here, consider the operation successful.
  326. if (completion) {
  327. dispatch_async(dispatch_get_main_queue(), ^{
  328. completion(nil);
  329. });
  330. }
  331. return;
  332. }
  333. NSString *revokeURLString = [NSString stringWithFormat:kRevokeTokenURLTemplate,
  334. [GIDSignInPreferences googleAuthorizationServer]];
  335. // Append logging parameter
  336. revokeURLString = [NSString stringWithFormat:@"%@?%@=%@&%@=%@",
  337. revokeURLString,
  338. kSDKVersionLoggingParameter,
  339. GIDVersion(),
  340. kEnvironmentLoggingParameter,
  341. GIDEnvironment()];
  342. NSURL *revokeURL = [NSURL URLWithString:revokeURLString];
  343. NSMutableURLRequest *revokeRequest = [NSMutableURLRequest requestWithURL:revokeURL];
  344. [revokeRequest setHTTPMethod:@"POST"];
  345. NSString *postString = [NSString stringWithFormat:@"token=%@", token];
  346. [revokeRequest setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
  347. GTMAppAuthFetcherAuthorization *authorization =
  348. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  349. [_httpFetcher fetchURLRequest:revokeRequest
  350. withAuthorizer:authorization
  351. withComment:@"GIDSignIn: revoke tokens"
  352. completion:^(NSData *data, NSError *error) {
  353. // Revoking an already revoked token seems always successful, which helps us here.
  354. if (!error) {
  355. [self signOut];
  356. }
  357. if (completion) {
  358. dispatch_async(dispatch_get_main_queue(), ^{
  359. completion(error);
  360. });
  361. }
  362. }];
  363. }
  364. #pragma mark - Custom getters and setters
  365. + (GIDSignIn *)sharedInstance {
  366. static dispatch_once_t once;
  367. static GIDSignIn *sharedInstance;
  368. dispatch_once(&once, ^{
  369. sharedInstance = [[self alloc] initPrivate];
  370. });
  371. return sharedInstance;
  372. }
  373. #pragma mark - Private methods
  374. - (id)initPrivate {
  375. id<GIDKeychainHandler> keychainHandler = [[GIDKeychainHandler alloc] init];
  376. id<GIDHTTPFetcher> httpFetcher = [[GIDHTTPFetcher alloc] init];
  377. id<GIDAuthorizationFlowProcessor> authorizationFlowProcessor =
  378. [[GIDAuthorizationFlowProcessor alloc] init];
  379. id<GIDProfileDataFetcher> profileDataFetcher = [[GIDProfileDataFetcher alloc] init];
  380. return [self initWithKeychainHandler:keychainHandler
  381. httpFetcher:httpFetcher
  382. profileDataFetcher:profileDataFetcher
  383. authorizationFlowProcessor:authorizationFlowProcessor];
  384. }
  385. - (instancetype)initWithKeychainHandler:(id<GIDKeychainHandler>)keychainHandler
  386. httpFetcher:(id<GIDHTTPFetcher>)httpFetcher
  387. profileDataFetcher:(id<GIDProfileDataFetcher>)profileDataFetcher
  388. authorizationFlowProcessor:
  389. (id<GIDAuthorizationFlowProcessor>)authorizationFlowProcessor {
  390. self = [super init];
  391. if (self) {
  392. // Get the bundle of the current executable.
  393. NSBundle *bundle = NSBundle.mainBundle;
  394. // If we have a bundle, try to set the active configuration from the bundle's Info.plist.
  395. if (bundle) {
  396. _configuration = [GIDSignIn configurationFromBundle:bundle];
  397. }
  398. // Check to see if the 3P app is being run for the first time after a fresh install.
  399. BOOL isFreshInstall = [self isFreshInstall];
  400. // If this is a fresh install, ensure that any pre-existing keychain data is purged.
  401. if (isFreshInstall) {
  402. [_keychainHandler removeAllKeychainEntries];
  403. }
  404. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  405. // Perform migration of auth state from old (before 5.0) versions of the SDK if needed.
  406. NSURL *tokenEndpointURL = [GIDSignInPreferences tokenEndpointURL];
  407. [GIDAuthStateMigration migrateIfNeededWithTokenURL:tokenEndpointURL
  408. callbackPath:kBrowserCallbackPath
  409. keychainName:kGTMAppAuthKeychainName
  410. isFreshInstall:isFreshInstall];
  411. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  412. _keychainHandler = keychainHandler;
  413. _httpFetcher = httpFetcher;
  414. _authorizationFlowProcessor = authorizationFlowProcessor;
  415. _profileDataFetcher = profileDataFetcher;
  416. }
  417. return self;
  418. }
  419. // Does sanity check for parameters and then authenticates if necessary.
  420. - (void)signInWithOptions:(GIDSignInInternalOptions *)options {
  421. // Options for continuation are not the options we want to cache. The purpose of caching the
  422. // options in the first place is to provide continuation flows with a starting place from which to
  423. // derive suitable options for the continuation!
  424. if (!options.continuation) {
  425. _currentOptions = options;
  426. }
  427. if (options.interactive) {
  428. // Ensure that a configuration has been provided.
  429. if (!_configuration) {
  430. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  431. [NSException raise:NSInvalidArgumentException
  432. format:@"No active configuration. Make sure GIDClientID is set in Info.plist."];
  433. return;
  434. }
  435. // Explicitly throw exception for missing client ID here. This must come before
  436. // scheme check because schemes rely on reverse client IDs.
  437. [self assertValidParameters];
  438. [self assertValidPresentingViewController];
  439. // If the application does not support the required URL schemes tell the developer so.
  440. GIDSignInCallbackSchemes *schemes =
  441. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  442. NSArray<NSString *> *unsupportedSchemes = [schemes unsupportedSchemes];
  443. if (unsupportedSchemes.count != 0) {
  444. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  445. [NSException raise:NSInvalidArgumentException
  446. format:@"Your app is missing support for the following URL schemes: %@",
  447. [unsupportedSchemes componentsJoinedByString:@", "]];
  448. }
  449. }
  450. // If this is a non-interactive flow, use cached authentication if possible.
  451. if (!options.interactive && _currentUser) {
  452. [_currentUser refreshTokensIfNeededWithCompletion:^(GIDGoogleUser *unused, NSError *error) {
  453. if (error) {
  454. [self authenticateWithOptions:options];
  455. } else {
  456. if (options.completion) {
  457. self->_currentOptions = nil;
  458. dispatch_async(dispatch_get_main_queue(), ^{
  459. GIDSignInResult *signInResult =
  460. [[GIDSignInResult alloc] initWithGoogleUser:self->_currentUser serverAuthCode:nil];
  461. options.completion(signInResult, nil);
  462. });
  463. }
  464. }
  465. }];
  466. } else {
  467. [self authenticateWithOptions:options];
  468. }
  469. }
  470. #pragma mark - Authentication flow
  471. - (void)authenticateInteractivelyWithOptions:(GIDSignInInternalOptions *)options {
  472. NSString *emmSupport;
  473. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  474. emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  475. #elif TARGET_OS_MACCATALYST || TARGET_OS_OSX
  476. emmSupport = nil;
  477. #endif // TARGET_OS_MACCATALYST || TARGET_OS_OSX
  478. [_authorizationFlowProcessor startWithOptions:options
  479. emmSupport:(NSString *)emmSupport
  480. completion:^(OIDAuthorizationResponse *authorizationResponse,
  481. NSError *error) {
  482. [self processAuthorizationResponse:authorizationResponse
  483. error:error
  484. emmSupport:emmSupport];
  485. }];
  486. }
  487. - (void)processAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse
  488. error:(NSError *)error
  489. emmSupport:(NSString *)emmSupport{
  490. if (_restarting) {
  491. // The auth flow is restarting, so the work here would be performed in the next round.
  492. _restarting = NO;
  493. return;
  494. }
  495. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  496. authFlow.emmSupport = emmSupport;
  497. if (authorizationResponse) {
  498. if (authorizationResponse.authorizationCode.length) {
  499. authFlow.authState = [[OIDAuthState alloc]
  500. initWithAuthorizationResponse:authorizationResponse];
  501. // perform auth code exchange
  502. [self maybeFetchToken:authFlow];
  503. } else {
  504. // There was a failure, convert to appropriate error code.
  505. NSString *errorString;
  506. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  507. NSDictionary<NSString *, NSObject *> *params = authorizationResponse.additionalParameters;
  508. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  509. if (authFlow.emmSupport) {
  510. [authFlow wait];
  511. BOOL isEMMError = [[GIDEMMErrorHandler sharedInstance]
  512. handleErrorFromResponse:params
  513. completion:^{
  514. [authFlow next];
  515. }];
  516. if (isEMMError) {
  517. errorCode = kGIDSignInErrorCodeEMM;
  518. }
  519. }
  520. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  521. errorString = (NSString *)params[kOAuth2ErrorKeyName];
  522. if ([errorString isEqualToString:kOAuth2AccessDenied]) {
  523. errorCode = kGIDSignInErrorCodeCanceled;
  524. }
  525. authFlow.error = [self errorWithString:errorString code:errorCode];
  526. }
  527. } else {
  528. NSString *errorString = [error localizedDescription];
  529. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  530. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow) {
  531. // The user has canceled the flow at the iOS modal dialog.
  532. errorString = kUserCanceledError;
  533. errorCode = kGIDSignInErrorCodeCanceled;
  534. }
  535. authFlow.error = [self errorWithString:errorString code:errorCode];
  536. }
  537. [self addDecodeIdTokenCallback:authFlow];
  538. [self addSaveAuthCallback:authFlow];
  539. [self addCompletionCallback:authFlow];
  540. }
  541. // Perform authentication with the provided options.
  542. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options {
  543. // If this is an interactive flow, we're not going to try to restore any saved auth state.
  544. if (options.interactive) {
  545. [self authenticateInteractivelyWithOptions:options];
  546. return;
  547. }
  548. // Try retrieving an authorization object from the keychain.
  549. OIDAuthState *authState = [_keychainHandler loadAuthState];
  550. if (![authState isAuthorized]) {
  551. // No valid auth in keychain, per documentation/spec, notify callback of failure.
  552. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  553. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  554. userInfo:nil];
  555. if (options.completion) {
  556. _currentOptions = nil;
  557. dispatch_async(dispatch_get_main_queue(), ^{
  558. options.completion(nil, error);
  559. });
  560. }
  561. return;
  562. }
  563. // Complete the auth flow using saved auth in keychain.
  564. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  565. authFlow.authState = authState;
  566. [self maybeFetchToken:authFlow];
  567. [self addDecodeIdTokenCallback:authFlow];
  568. [self addSaveAuthCallback:authFlow];
  569. [self addCompletionCallback:authFlow];
  570. }
  571. // Fetches the access token if necessary as part of the auth flow.
  572. - (void)maybeFetchToken:(GIDAuthFlow *)authFlow {
  573. OIDAuthState *authState = authFlow.authState;
  574. // Do nothing if we have an auth flow error or a restored access token that isn't near expiration.
  575. if (authFlow.error ||
  576. (authState.lastTokenResponse.accessToken &&
  577. [authState.lastTokenResponse.accessTokenExpirationDate timeIntervalSinceNow] >
  578. kMinimumRestoredAccessTokenTimeToExpire)) {
  579. return;
  580. }
  581. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  582. if (_currentOptions.configuration.serverClientID) {
  583. additionalParameters[kAudienceParameter] = _currentOptions.configuration.serverClientID;
  584. }
  585. if (_currentOptions.configuration.openIDRealm) {
  586. additionalParameters[kOpenIDRealmParameter] = _currentOptions.configuration.openIDRealm;
  587. }
  588. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  589. NSDictionary<NSString *, NSObject *> *params =
  590. authState.lastAuthorizationResponse.additionalParameters;
  591. NSString *passcodeInfoRequired = (NSString *)params[kEMMPasscodeInfoRequiredKeyName];
  592. [additionalParameters addEntriesFromDictionary:
  593. [GIDEMMSupport parametersWithParameters:@{}
  594. emmSupport:authFlow.emmSupport
  595. isPasscodeInfoRequired:passcodeInfoRequired.length > 0]];
  596. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  597. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  598. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  599. OIDTokenRequest *tokenRequest;
  600. if (!authState.lastTokenResponse.accessToken &&
  601. authState.lastAuthorizationResponse.authorizationCode) {
  602. tokenRequest = [authState.lastAuthorizationResponse
  603. tokenExchangeRequestWithAdditionalParameters:additionalParameters];
  604. } else {
  605. [additionalParameters
  606. addEntriesFromDictionary:authState.lastTokenResponse.request.additionalParameters];
  607. tokenRequest = [authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  608. }
  609. [authFlow wait];
  610. [OIDAuthorizationService
  611. performTokenRequest:tokenRequest
  612. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  613. NSError *_Nullable error) {
  614. [authState updateWithTokenResponse:tokenResponse error:error];
  615. authFlow.error = error;
  616. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  617. if (authFlow.emmSupport) {
  618. [GIDEMMSupport handleTokenFetchEMMError:error completion:^(NSError *error) {
  619. authFlow.error = error;
  620. [authFlow next];
  621. }];
  622. } else {
  623. [authFlow next];
  624. }
  625. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  626. [authFlow next];
  627. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  628. }];
  629. }
  630. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  631. - (void)addSaveAuthCallback:(GIDAuthFlow *)authFlow {
  632. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  633. [authFlow addCallback:^() {
  634. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  635. OIDAuthState *authState = handlerAuthFlow.authState;
  636. if (authState && !handlerAuthFlow.error) {
  637. if (![self->_keychainHandler saveAuthState:authState]) {
  638. handlerAuthFlow.error = [self errorWithString:kKeychainError
  639. code:kGIDSignInErrorCodeKeychain];
  640. return;
  641. }
  642. if (self->_currentOptions.addScopesFlow) {
  643. [self->_currentUser updateWithTokenResponse:authState.lastTokenResponse
  644. authorizationResponse:authState.lastAuthorizationResponse
  645. profileData:handlerAuthFlow.profileData];
  646. } else {
  647. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState
  648. profileData:handlerAuthFlow.profileData];
  649. self.currentUser = user;
  650. }
  651. }
  652. }];
  653. }
  654. // Adds a callback to the auth flow to extract user data from the ID token where available and
  655. // make a userinfo request if necessary.
  656. - (void)addDecodeIdTokenCallback:(GIDAuthFlow *)authFlow {
  657. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  658. [authFlow addCallback:^() {
  659. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  660. OIDAuthState *authState = handlerAuthFlow.authState;
  661. if (!authState || handlerAuthFlow.error) {
  662. return;
  663. }
  664. [handlerAuthFlow wait];
  665. [self->_profileDataFetcher
  666. fetchProfileDataWithAuthState:(OIDAuthState *)authState
  667. completion:^(GIDProfileData *_Nullable profileData,
  668. NSError *_Nullable error) {
  669. if (error) {
  670. handlerAuthFlow.error = error;
  671. } else {
  672. handlerAuthFlow.profileData = profileData;
  673. }
  674. [handlerAuthFlow next];
  675. }];
  676. }];
  677. }
  678. // Adds a callback to the auth flow to complete the flow by calling the sign-in callback.
  679. - (void)addCompletionCallback:(GIDAuthFlow *)authFlow {
  680. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  681. [authFlow addCallback:^() {
  682. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  683. if (self->_currentOptions.completion) {
  684. GIDSignInCompletion completion = self->_currentOptions.completion;
  685. self->_currentOptions = nil;
  686. dispatch_async(dispatch_get_main_queue(), ^{
  687. if (handlerAuthFlow.error) {
  688. completion(nil, handlerAuthFlow.error);
  689. } else {
  690. OIDAuthState *authState = handlerAuthFlow.authState;
  691. NSString *_Nullable serverAuthCode =
  692. [authState.lastTokenResponse.additionalParameters[@"server_code"] copy];
  693. GIDSignInResult *signInResult =
  694. [[GIDSignInResult alloc] initWithGoogleUser:self->_currentUser
  695. serverAuthCode:serverAuthCode];
  696. completion(signInResult, nil);
  697. }
  698. });
  699. }
  700. }];
  701. }
  702. // Parse incoming URL from the Google Device Policy app.
  703. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  704. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  705. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  706. NSObject<NSCopying> *actionParam = params[@"action"];
  707. NSString *actionString =
  708. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  709. if (![@"restart_auth" isEqualToString:actionString]) {
  710. return NO;
  711. }
  712. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  713. if (!_currentOptions.presentingViewController) {
  714. return NO;
  715. }
  716. #elif TARGET_OS_OSX
  717. if (!_currentOptions.presentingWindow) {
  718. return NO;
  719. }
  720. #endif // TARGET_OS_OSX
  721. if (!_authorizationFlowProcessor.isStarted) {
  722. return NO;
  723. }
  724. _restarting = YES;
  725. [_authorizationFlowProcessor cancelAuthenticationFlow];
  726. _restarting = NO;
  727. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  728. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  729. // so we need to wait until the previous presentation is completely gone to ensure the right
  730. // anchor window is used here.
  731. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  732. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  733. dispatch_get_main_queue(), ^{
  734. [self signInWithOptions:[self->_currentOptions optionsWithExtraParameters:extraParameters
  735. forContinuation:YES]];
  736. });
  737. return YES;
  738. }
  739. #pragma mark - Helpers
  740. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  741. if (errorString == nil) {
  742. errorString = @"Unknown error";
  743. }
  744. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  745. return [NSError errorWithDomain:kGIDSignInErrorDomain
  746. code:code
  747. userInfo:errorDict];
  748. }
  749. + (BOOL)isOperatingSystemAtLeast9 {
  750. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  751. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  752. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  753. }
  754. // Asserts the parameters being valid.
  755. - (void)assertValidParameters {
  756. if (![_currentOptions.configuration.clientID length]) {
  757. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  758. [NSException raise:NSInvalidArgumentException
  759. format:@"You must specify |clientID| in |GIDConfiguration|"];
  760. }
  761. }
  762. // Assert that the presenting view controller has been set.
  763. - (void)assertValidPresentingViewController {
  764. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  765. if (!_currentOptions.presentingViewController)
  766. #elif TARGET_OS_OSX
  767. if (!_currentOptions.presentingWindow)
  768. #endif // TARGET_OS_OSX
  769. {
  770. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  771. [NSException raise:NSInvalidArgumentException
  772. format:@"|presentingViewController| must be set."];
  773. }
  774. }
  775. // Checks whether or not this is the first time the app runs.
  776. - (BOOL)isFreshInstall {
  777. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  778. if ([defaults boolForKey:kAppHasRunBeforeKey]) {
  779. return NO;
  780. }
  781. [defaults setBool:YES forKey:kAppHasRunBeforeKey];
  782. return YES;
  783. }
  784. // Try to retrieve a configuration value from an |NSBundle|'s Info.plist for a given key.
  785. + (nullable NSString *)configValueFromBundle:(NSBundle *)bundle forKey:(NSString *)key {
  786. NSString *value;
  787. id configValue = [bundle objectForInfoDictionaryKey:key];
  788. if ([configValue isKindOfClass:[NSString class]]) {
  789. value = configValue;
  790. }
  791. return value;
  792. }
  793. // Try to generate a |GIDConfiguration| from an |NSBundle|'s Info.plist.
  794. + (nullable GIDConfiguration *)configurationFromBundle:(NSBundle *)bundle {
  795. GIDConfiguration *configuration;
  796. // Retrieve any valid config parameters from the bundle's Info.plist.
  797. NSString *clientID = [GIDSignIn configValueFromBundle:bundle forKey:kConfigClientIDKey];
  798. NSString *serverClientID = [GIDSignIn configValueFromBundle:bundle
  799. forKey:kConfigServerClientIDKey];
  800. NSString *hostedDomain = [GIDSignIn configValueFromBundle:bundle forKey:kConfigHostedDomainKey];
  801. NSString *openIDRealm = [GIDSignIn configValueFromBundle:bundle forKey:kConfigOpenIDRealmKey];
  802. // If we have at least a client ID, try to construct a configuration.
  803. if (clientID) {
  804. configuration = [[GIDConfiguration alloc] initWithClientID:clientID
  805. serverClientID:serverClientID
  806. hostedDomain:hostedDomain
  807. openIDRealm:openIDRealm];
  808. }
  809. return configuration;
  810. }
  811. @end
  812. NS_ASSUME_NONNULL_END