GIDSignIn.m 40 KB

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