GIDSignIn.m 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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/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/GIDHTTPFetcher/API/GIDHTTPFetcher.h"
  23. #import "GoogleSignIn/Sources/GIDHTTPFetcher/Implementations/GIDHTTPFetcher.h"
  24. #import "GoogleSignIn/Sources/GIDEMMSupport.h"
  25. #import "GoogleSignIn/Sources/GIDKeychainHandler/API/GIDKeychainHandler.h"
  26. #import "GoogleSignIn/Sources/GIDKeychainHandler/Implementations/GIDKeychainHandler.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 get user info.
  69. static NSString *const kUserInfoURLTemplate = @"https://%@/oauth2/v3/userinfo";
  70. // The URL template for the URL to revoke the token.
  71. static NSString *const kRevokeTokenURLTemplate = @"https://%@/o/oauth2/revoke";
  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. // Basic profile (Fat ID Token / userinfo endpoint) keys
  81. static NSString *const kBasicProfileEmailKey = @"email";
  82. static NSString *const kBasicProfilePictureKey = @"picture";
  83. static NSString *const kBasicProfileNameKey = @"name";
  84. static NSString *const kBasicProfileGivenNameKey = @"given_name";
  85. static NSString *const kBasicProfileFamilyNameKey = @"family_name";
  86. // Parameters in the callback URL coming back from browser.
  87. static NSString *const kAuthorizationCodeKeyName = @"code";
  88. static NSString *const kOAuth2ErrorKeyName = @"error";
  89. static NSString *const kOAuth2AccessDenied = @"access_denied";
  90. static NSString *const kEMMPasscodeInfoRequiredKeyName = @"emm_passcode_info_required";
  91. // Error string for unavailable keychain.
  92. static NSString *const kKeychainError = @"keychain error";
  93. // Error string for user cancelations.
  94. static NSString *const kUserCanceledError = @"The user canceled the sign-in flow.";
  95. // User preference key to detect fresh install of the app.
  96. static NSString *const kAppHasRunBeforeKey = @"GID_AppHasRunBefore";
  97. // The delay before the new sign-in flow can be presented after the existing one is cancelled.
  98. static const NSTimeInterval kPresentationDelayAfterCancel = 1.0;
  99. // Parameters for the auth and token exchange endpoints.
  100. static NSString *const kAudienceParameter = @"audience";
  101. // See b/11669751 .
  102. static NSString *const kOpenIDRealmParameter = @"openid.realm";
  103. // Minimum time to expiration for a restored access token.
  104. static const NSTimeInterval kMinimumRestoredAccessTokenTimeToExpire = 600.0;
  105. // Info.plist config keys
  106. static NSString *const kConfigClientIDKey = @"GIDClientID";
  107. static NSString *const kConfigServerClientIDKey = @"GIDServerClientID";
  108. static NSString *const kConfigHostedDomainKey = @"GIDHostedDomain";
  109. static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
  110. // The callback queue used for authentication flow.
  111. @interface GIDAuthFlow : GIDCallbackQueue
  112. @property(nonatomic, strong, nullable) OIDAuthState *authState;
  113. @property(nonatomic, strong, nullable) NSError *error;
  114. @property(nonatomic, copy, nullable) NSString *emmSupport;
  115. @property(nonatomic, nullable) GIDProfileData *profileData;
  116. @end
  117. @implementation GIDAuthFlow
  118. @end
  119. @implementation GIDSignIn {
  120. // This value is used when sign-in flows are resumed via the handling of a URL. Its value is
  121. // set when a sign-in flow is begun via |signInWithOptions:| when the options passed don't
  122. // represent a sign in continuation.
  123. GIDSignInInternalOptions *_currentOptions;
  124. // Flag to indicate that the auth flow is restarting.
  125. BOOL _restarting;
  126. id<GIDKeychainHandler> _keychainHandler;
  127. // The class to fetches data from a url end point.
  128. id<GIDHTTPFetcher> _httpFetcher;
  129. // The class to control the authorization flow.
  130. id<GIDAuthorizationFlowProcessor> _authorizationFlowProcessor;
  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 ([_authorizationFlowProcessor resumeExternalUserAgentFlowWithURL:url]) {
  141. return YES;
  142. }
  143. return NO;
  144. }
  145. // Check if the callback path matches the expected one for a URL from Google Device Policy app.
  146. if ([url.path isEqual:kEMMCallbackPath]) {
  147. return [self handleDevicePolicyAppURL:url];
  148. }
  149. return NO;
  150. }
  151. - (BOOL)hasPreviousSignIn {
  152. if ([_currentUser.authState isAuthorized]) {
  153. return YES;
  154. }
  155. OIDAuthState *authState = [_keychainHandler loadAuthState];
  156. return [authState isAuthorized];
  157. }
  158. - (void)restorePreviousSignInWithCompletion:(nullable void (^)(GIDGoogleUser *_Nullable user,
  159. NSError *_Nullable error))completion {
  160. [self signInWithOptions:[GIDSignInInternalOptions silentOptionsWithCompletion:
  161. ^(GIDSignInResult *signInResult, NSError *error) {
  162. if (signInResult) {
  163. completion(signInResult.user, nil);
  164. } else {
  165. completion(nil, error);
  166. }
  167. }]];
  168. }
  169. - (BOOL)restorePreviousSignInNoRefresh {
  170. if (_currentUser) {
  171. return YES;
  172. }
  173. // Try retrieving an authorization object from the keychain.
  174. OIDAuthState *authState = [_keychainHandler loadAuthState];
  175. if (!authState) {
  176. return NO;
  177. }
  178. // Restore current user without refreshing the access token.
  179. OIDIDToken *idToken =
  180. [[OIDIDToken alloc] initWithIDTokenString:authState.lastTokenResponse.idToken];
  181. GIDProfileData *profileData = [self profileDataWithIDToken:idToken];
  182. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState profileData:profileData];
  183. self.currentUser = user;
  184. return YES;
  185. }
  186. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  187. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  188. hint:(nullable NSString *)hint
  189. completion:(nullable GIDSignInCompletion)completion {
  190. GIDSignInInternalOptions *options =
  191. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  192. presentingViewController:presentingViewController
  193. loginHint:hint
  194. addScopesFlow:NO
  195. completion:completion];
  196. [self signInWithOptions:options];
  197. }
  198. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  199. hint:(nullable NSString *)hint
  200. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  201. completion:(nullable GIDSignInCompletion)completion {
  202. GIDSignInInternalOptions *options =
  203. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  204. presentingViewController:presentingViewController
  205. loginHint:hint
  206. addScopesFlow:NO
  207. scopes:additionalScopes
  208. completion:completion];
  209. [self signInWithOptions:options];
  210. }
  211. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  212. completion:(nullable GIDSignInCompletion)completion {
  213. [self signInWithPresentingViewController:presentingViewController
  214. hint:nil
  215. completion:completion];
  216. }
  217. - (void)addScopes:(NSArray<NSString *> *)scopes
  218. presentingViewController:(UIViewController *)presentingViewController
  219. completion:(nullable GIDSignInCompletion)completion {
  220. GIDConfiguration *configuration = self.currentUser.configuration;
  221. GIDSignInInternalOptions *options =
  222. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  223. presentingViewController:presentingViewController
  224. loginHint:self.currentUser.profile.email
  225. addScopesFlow:YES
  226. completion:completion];
  227. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  228. NSMutableSet<NSString *> *grantedScopes =
  229. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  230. // Check to see if all requested scopes have already been granted.
  231. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  232. // All requested scopes have already been granted, notify callback of failure.
  233. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  234. code:kGIDSignInErrorCodeScopesAlreadyGranted
  235. userInfo:nil];
  236. if (completion) {
  237. dispatch_async(dispatch_get_main_queue(), ^{
  238. completion(nil, error);
  239. });
  240. }
  241. return;
  242. }
  243. // Use the union of granted and requested scopes.
  244. [grantedScopes unionSet:requestedScopes];
  245. options.scopes = [grantedScopes allObjects];
  246. [self signInWithOptions:options];
  247. }
  248. #elif TARGET_OS_OSX
  249. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  250. hint:(nullable NSString *)hint
  251. completion:(nullable GIDSignInCompletion)completion {
  252. GIDSignInInternalOptions *options =
  253. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  254. presentingWindow:presentingWindow
  255. loginHint:hint
  256. addScopesFlow:NO
  257. completion:completion];
  258. [self signInWithOptions:options];
  259. }
  260. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  261. completion:(nullable GIDSignInCompletion)completion {
  262. [self signInWithPresentingWindow:presentingWindow
  263. hint:nil
  264. completion:completion];
  265. }
  266. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  267. hint:(nullable NSString *)hint
  268. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  269. completion:(nullable GIDSignInCompletion)completion {
  270. GIDSignInInternalOptions *options =
  271. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  272. presentingWindow:presentingWindow
  273. loginHint:hint
  274. addScopesFlow:NO
  275. scopes:additionalScopes
  276. completion:completion];
  277. [self signInWithOptions:options];
  278. }
  279. - (void)addScopes:(NSArray<NSString *> *)scopes
  280. presentingWindow:(NSWindow *)presentingWindow
  281. completion:(nullable GIDSignInCompletion)completion {
  282. GIDConfiguration *configuration = self.currentUser.configuration;
  283. GIDSignInInternalOptions *options =
  284. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  285. presentingWindow:presentingWindow
  286. loginHint:self.currentUser.profile.email
  287. addScopesFlow:YES
  288. completion:completion];
  289. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  290. NSMutableSet<NSString *> *grantedScopes =
  291. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  292. // Check to see if all requested scopes have already been granted.
  293. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  294. // All requested scopes have already been granted, notify callback of failure.
  295. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  296. code:kGIDSignInErrorCodeScopesAlreadyGranted
  297. userInfo:nil];
  298. if (completion) {
  299. dispatch_async(dispatch_get_main_queue(), ^{
  300. completion(nil, error);
  301. });
  302. }
  303. return;
  304. }
  305. // Use the union of granted and requested scopes.
  306. [grantedScopes unionSet:requestedScopes];
  307. options.scopes = [grantedScopes allObjects];
  308. [self signInWithOptions:options];
  309. }
  310. #endif // TARGET_OS_OSX
  311. - (void)signOut {
  312. // Clear the current user if there is one.
  313. if (_currentUser) {
  314. self.currentUser = nil;
  315. }
  316. // Remove all state from the keychain.
  317. [_keychainHandler removeAllKeychainEntries];
  318. }
  319. - (void)disconnectWithCompletion:(nullable GIDDisconnectCompletion)completion {
  320. OIDAuthState *authState = _currentUser.authState;
  321. if (!authState) {
  322. // Even the user is not signed in right now, we still need to remove any token saved in the
  323. // keychain.
  324. authState = [_keychainHandler loadAuthState];
  325. }
  326. // Either access or refresh token would work, but we won't have access token if the auth is
  327. // retrieved from keychain.
  328. NSString *token = authState.lastTokenResponse.accessToken;
  329. if (!token) {
  330. token = authState.lastTokenResponse.refreshToken;
  331. }
  332. if (!token) {
  333. [self signOut];
  334. // Nothing to do here, consider the operation successful.
  335. if (completion) {
  336. dispatch_async(dispatch_get_main_queue(), ^{
  337. completion(nil);
  338. });
  339. }
  340. return;
  341. }
  342. NSString *revokeURLString = [NSString stringWithFormat:kRevokeTokenURLTemplate,
  343. [GIDSignInPreferences googleAuthorizationServer]];
  344. // Append logging parameter
  345. revokeURLString = [NSString stringWithFormat:@"%@?%@=%@&%@=%@",
  346. revokeURLString,
  347. kSDKVersionLoggingParameter,
  348. GIDVersion(),
  349. kEnvironmentLoggingParameter,
  350. GIDEnvironment()];
  351. NSURL *revokeURL = [NSURL URLWithString:revokeURLString];
  352. NSMutableURLRequest *revokeRequest = [NSMutableURLRequest requestWithURL:revokeURL];
  353. [revokeRequest setHTTPMethod:@"POST"];
  354. NSString *postString = [NSString stringWithFormat:@"token=%@", token];
  355. [revokeRequest setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
  356. GTMAppAuthFetcherAuthorization *authorization =
  357. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  358. [_httpFetcher fetchURLRequest:revokeRequest
  359. withAuthorizer:authorization
  360. withComment:@"GIDSignIn: revoke tokens"
  361. completion:^(NSData *data, NSError *error) {
  362. // Revoking an already revoked token seems always successful, which helps us here.
  363. if (!error) {
  364. [self signOut];
  365. }
  366. if (completion) {
  367. dispatch_async(dispatch_get_main_queue(), ^{
  368. completion(error);
  369. });
  370. }
  371. }];
  372. }
  373. #pragma mark - Custom getters and setters
  374. + (GIDSignIn *)sharedInstance {
  375. static dispatch_once_t once;
  376. static GIDSignIn *sharedInstance;
  377. dispatch_once(&once, ^{
  378. sharedInstance = [[self alloc] initPrivate];
  379. });
  380. return sharedInstance;
  381. }
  382. #pragma mark - Private methods
  383. - (id)initPrivate {
  384. id<GIDKeychainHandler> keychainHandler = [[GIDKeychainHandler alloc] init];
  385. id<GIDHTTPFetcher> httpFetcher = [[GIDHTTPFetcher alloc] init];
  386. id<GIDAuthorizationFlowProcessor> authorizationFlowProcessor =
  387. [[GIDAuthorizationFlowProcessor alloc] init];
  388. return [self initWithKeychainHandler:keychainHandler
  389. httpFetcher:httpFetcher
  390. authorizationFlowProcessor:authorizationFlowProcessor];
  391. }
  392. - (instancetype)initWithKeychainHandler:(id<GIDKeychainHandler>)keychainHandler
  393. httpFetcher:(id<GIDHTTPFetcher>)httpFetcher
  394. authorizationFlowProcessor:(id<GIDAuthorizationFlowProcessor>)authorizationFlowProcessor {
  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. _authorizationFlowProcessor = authorizationFlowProcessor;
  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. NSString *emmSupport;
  477. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  478. emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  479. #elif TARGET_OS_MACCATALYST || TARGET_OS_OSX
  480. emmSupport = nil;
  481. #endif // TARGET_OS_MACCATALYST || TARGET_OS_OSX
  482. [_authorizationFlowProcessor startWithOptions:options
  483. emmSupport:(NSString *)emmSupport
  484. completion:^(OIDAuthorizationResponse *authorizationResponse,
  485. NSError *error) {
  486. [self processAuthorizationResponse:authorizationResponse
  487. error:error
  488. emmSupport:emmSupport];
  489. }];
  490. }
  491. - (void)processAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse
  492. error:(NSError *)error
  493. emmSupport:(NSString *)emmSupport{
  494. if (_restarting) {
  495. // The auth flow is restarting, so the work here would be performed in the next round.
  496. _restarting = NO;
  497. return;
  498. }
  499. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  500. authFlow.emmSupport = emmSupport;
  501. if (authorizationResponse) {
  502. if (authorizationResponse.authorizationCode.length) {
  503. authFlow.authState = [[OIDAuthState alloc]
  504. initWithAuthorizationResponse:authorizationResponse];
  505. // perform auth code exchange
  506. [self maybeFetchToken:authFlow];
  507. } else {
  508. // There was a failure, convert to appropriate error code.
  509. NSString *errorString;
  510. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  511. NSDictionary<NSString *, NSObject *> *params = authorizationResponse.additionalParameters;
  512. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  513. if (authFlow.emmSupport) {
  514. [authFlow wait];
  515. BOOL isEMMError = [[GIDEMMErrorHandler sharedInstance]
  516. handleErrorFromResponse:params
  517. completion:^{
  518. [authFlow next];
  519. }];
  520. if (isEMMError) {
  521. errorCode = kGIDSignInErrorCodeEMM;
  522. }
  523. }
  524. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  525. errorString = (NSString *)params[kOAuth2ErrorKeyName];
  526. if ([errorString isEqualToString:kOAuth2AccessDenied]) {
  527. errorCode = kGIDSignInErrorCodeCanceled;
  528. }
  529. authFlow.error = [self errorWithString:errorString code:errorCode];
  530. }
  531. } else {
  532. NSString *errorString = [error localizedDescription];
  533. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  534. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow) {
  535. // The user has canceled the flow at the iOS modal dialog.
  536. errorString = kUserCanceledError;
  537. errorCode = kGIDSignInErrorCodeCanceled;
  538. }
  539. authFlow.error = [self errorWithString:errorString code:errorCode];
  540. }
  541. [self addDecodeIdTokenCallback:authFlow];
  542. [self addSaveAuthCallback:authFlow];
  543. [self addCompletionCallback:authFlow];
  544. }
  545. // Perform authentication with the provided options.
  546. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options {
  547. // If this is an interactive flow, we're not going to try to restore any saved auth state.
  548. if (options.interactive) {
  549. [self authenticateInteractivelyWithOptions:options];
  550. return;
  551. }
  552. // Try retrieving an authorization object from the keychain.
  553. OIDAuthState *authState = [_keychainHandler loadAuthState];
  554. if (![authState isAuthorized]) {
  555. // No valid auth in keychain, per documentation/spec, notify callback of failure.
  556. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  557. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  558. userInfo:nil];
  559. if (options.completion) {
  560. _currentOptions = nil;
  561. dispatch_async(dispatch_get_main_queue(), ^{
  562. options.completion(nil, error);
  563. });
  564. }
  565. return;
  566. }
  567. // Complete the auth flow using saved auth in keychain.
  568. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  569. authFlow.authState = authState;
  570. [self maybeFetchToken:authFlow];
  571. [self addDecodeIdTokenCallback:authFlow];
  572. [self addSaveAuthCallback:authFlow];
  573. [self addCompletionCallback:authFlow];
  574. }
  575. // Fetches the access token if necessary as part of the auth flow.
  576. - (void)maybeFetchToken:(GIDAuthFlow *)authFlow {
  577. OIDAuthState *authState = authFlow.authState;
  578. // Do nothing if we have an auth flow error or a restored access token that isn't near expiration.
  579. if (authFlow.error ||
  580. (authState.lastTokenResponse.accessToken &&
  581. [authState.lastTokenResponse.accessTokenExpirationDate timeIntervalSinceNow] >
  582. kMinimumRestoredAccessTokenTimeToExpire)) {
  583. return;
  584. }
  585. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  586. if (_currentOptions.configuration.serverClientID) {
  587. additionalParameters[kAudienceParameter] = _currentOptions.configuration.serverClientID;
  588. }
  589. if (_currentOptions.configuration.openIDRealm) {
  590. additionalParameters[kOpenIDRealmParameter] = _currentOptions.configuration.openIDRealm;
  591. }
  592. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  593. NSDictionary<NSString *, NSObject *> *params =
  594. authState.lastAuthorizationResponse.additionalParameters;
  595. NSString *passcodeInfoRequired = (NSString *)params[kEMMPasscodeInfoRequiredKeyName];
  596. [additionalParameters addEntriesFromDictionary:
  597. [GIDEMMSupport parametersWithParameters:@{}
  598. emmSupport:authFlow.emmSupport
  599. isPasscodeInfoRequired:passcodeInfoRequired.length > 0]];
  600. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  601. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  602. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  603. OIDTokenRequest *tokenRequest;
  604. if (!authState.lastTokenResponse.accessToken &&
  605. authState.lastAuthorizationResponse.authorizationCode) {
  606. tokenRequest = [authState.lastAuthorizationResponse
  607. tokenExchangeRequestWithAdditionalParameters:additionalParameters];
  608. } else {
  609. [additionalParameters
  610. addEntriesFromDictionary:authState.lastTokenResponse.request.additionalParameters];
  611. tokenRequest = [authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  612. }
  613. [authFlow wait];
  614. [OIDAuthorizationService
  615. performTokenRequest:tokenRequest
  616. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  617. NSError *_Nullable error) {
  618. [authState updateWithTokenResponse:tokenResponse error:error];
  619. authFlow.error = error;
  620. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  621. if (authFlow.emmSupport) {
  622. [GIDEMMSupport handleTokenFetchEMMError:error completion:^(NSError *error) {
  623. authFlow.error = error;
  624. [authFlow next];
  625. }];
  626. } else {
  627. [authFlow next];
  628. }
  629. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  630. [authFlow next];
  631. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  632. }];
  633. }
  634. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  635. - (void)addSaveAuthCallback:(GIDAuthFlow *)authFlow {
  636. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  637. [authFlow addCallback:^() {
  638. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  639. OIDAuthState *authState = handlerAuthFlow.authState;
  640. if (authState && !handlerAuthFlow.error) {
  641. if (![self->_keychainHandler saveAuthState:authState]) {
  642. handlerAuthFlow.error = [self errorWithString:kKeychainError
  643. code:kGIDSignInErrorCodeKeychain];
  644. return;
  645. }
  646. if (self->_currentOptions.addScopesFlow) {
  647. [self->_currentUser updateWithTokenResponse:authState.lastTokenResponse
  648. authorizationResponse:authState.lastAuthorizationResponse
  649. profileData:handlerAuthFlow.profileData];
  650. } else {
  651. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState
  652. profileData:handlerAuthFlow.profileData];
  653. self.currentUser = user;
  654. }
  655. }
  656. }];
  657. }
  658. // Adds a callback to the auth flow to extract user data from the ID token where available and
  659. // make a userinfo request if necessary.
  660. - (void)addDecodeIdTokenCallback:(GIDAuthFlow *)authFlow {
  661. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  662. [authFlow addCallback:^() {
  663. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  664. OIDAuthState *authState = handlerAuthFlow.authState;
  665. if (!authState || handlerAuthFlow.error) {
  666. return;
  667. }
  668. OIDIDToken *idToken =
  669. [[OIDIDToken alloc] initWithIDTokenString: authState.lastTokenResponse.idToken];
  670. // If the profile data are present in the ID token, use them.
  671. if (idToken) {
  672. handlerAuthFlow.profileData = [self profileDataWithIDToken:idToken];
  673. }
  674. // If we can't retrieve profile data from the ID token, make a userInfo request to fetch them.
  675. if (!handlerAuthFlow.profileData) {
  676. [handlerAuthFlow wait];
  677. NSString *infoString = [NSString stringWithFormat:kUserInfoURLTemplate,
  678. [GIDSignInPreferences googleUserInfoServer]];
  679. NSURL *infoURL = [NSURL URLWithString:infoString];
  680. NSMutableURLRequest *infoRequest = [NSMutableURLRequest requestWithURL:infoURL];
  681. GTMAppAuthFetcherAuthorization *authorization =
  682. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  683. [self->_httpFetcher fetchURLRequest:infoRequest
  684. withAuthorizer:authorization
  685. withComment:@"GIDSignIn: fetch basic profile info"
  686. completion:^(NSData *data, NSError *error) {
  687. if (data && !error) {
  688. NSError *jsonDeserializationError;
  689. NSDictionary<NSString *, NSString *> *profileDict =
  690. [NSJSONSerialization JSONObjectWithData:data
  691. options:NSJSONReadingMutableContainers
  692. error:&jsonDeserializationError];
  693. if (profileDict) {
  694. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  695. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  696. name:profileDict[kBasicProfileNameKey]
  697. givenName:profileDict[kBasicProfileGivenNameKey]
  698. familyName:profileDict[kBasicProfileFamilyNameKey]
  699. imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
  700. }
  701. }
  702. if (error) {
  703. handlerAuthFlow.error = error;
  704. }
  705. [handlerAuthFlow next];
  706. }];
  707. }
  708. }];
  709. }
  710. // Adds a callback to the auth flow to complete the flow by calling the sign-in callback.
  711. - (void)addCompletionCallback:(GIDAuthFlow *)authFlow {
  712. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  713. [authFlow addCallback:^() {
  714. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  715. if (self->_currentOptions.completion) {
  716. GIDSignInCompletion completion = self->_currentOptions.completion;
  717. self->_currentOptions = nil;
  718. dispatch_async(dispatch_get_main_queue(), ^{
  719. if (handlerAuthFlow.error) {
  720. completion(nil, handlerAuthFlow.error);
  721. } else {
  722. OIDAuthState *authState = handlerAuthFlow.authState;
  723. NSString *_Nullable serverAuthCode =
  724. [authState.lastTokenResponse.additionalParameters[@"server_code"] copy];
  725. GIDSignInResult *signInResult =
  726. [[GIDSignInResult alloc] initWithGoogleUser:self->_currentUser
  727. serverAuthCode:serverAuthCode];
  728. completion(signInResult, nil);
  729. }
  730. });
  731. }
  732. }];
  733. }
  734. // Parse incoming URL from the Google Device Policy app.
  735. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  736. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  737. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  738. NSObject<NSCopying> *actionParam = params[@"action"];
  739. NSString *actionString =
  740. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  741. if (![@"restart_auth" isEqualToString:actionString]) {
  742. return NO;
  743. }
  744. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  745. if (!_currentOptions.presentingViewController) {
  746. return NO;
  747. }
  748. #elif TARGET_OS_OSX
  749. if (!_currentOptions.presentingWindow) {
  750. return NO;
  751. }
  752. #endif // TARGET_OS_OSX
  753. if (!_authorizationFlowProcessor.isStarted) {
  754. return NO;
  755. }
  756. _restarting = YES;
  757. [_authorizationFlowProcessor cancelAuthenticationFlow];
  758. _restarting = NO;
  759. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  760. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  761. // so we need to wait until the previous presentation is completely gone to ensure the right
  762. // anchor window is used here.
  763. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  764. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  765. dispatch_get_main_queue(), ^{
  766. [self signInWithOptions:[self->_currentOptions optionsWithExtraParameters:extraParameters
  767. forContinuation:YES]];
  768. });
  769. return YES;
  770. }
  771. #pragma mark - Helpers
  772. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  773. if (errorString == nil) {
  774. errorString = @"Unknown error";
  775. }
  776. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  777. return [NSError errorWithDomain:kGIDSignInErrorDomain
  778. code:code
  779. userInfo:errorDict];
  780. }
  781. + (BOOL)isOperatingSystemAtLeast9 {
  782. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  783. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  784. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  785. }
  786. // Asserts the parameters being valid.
  787. - (void)assertValidParameters {
  788. if (![_currentOptions.configuration.clientID length]) {
  789. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  790. [NSException raise:NSInvalidArgumentException
  791. format:@"You must specify |clientID| in |GIDConfiguration|"];
  792. }
  793. }
  794. // Assert that the presenting view controller has been set.
  795. - (void)assertValidPresentingViewController {
  796. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  797. if (!_currentOptions.presentingViewController)
  798. #elif TARGET_OS_OSX
  799. if (!_currentOptions.presentingWindow)
  800. #endif // TARGET_OS_OSX
  801. {
  802. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  803. [NSException raise:NSInvalidArgumentException
  804. format:@"|presentingViewController| must be set."];
  805. }
  806. }
  807. // Checks whether or not this is the first time the app runs.
  808. - (BOOL)isFreshInstall {
  809. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  810. if ([defaults boolForKey:kAppHasRunBeforeKey]) {
  811. return NO;
  812. }
  813. [defaults setBool:YES forKey:kAppHasRunBeforeKey];
  814. return YES;
  815. }
  816. // Generates user profile from OIDIDToken.
  817. - (GIDProfileData *)profileDataWithIDToken:(OIDIDToken *)idToken {
  818. if (!idToken ||
  819. !idToken.claims[kBasicProfilePictureKey] ||
  820. !idToken.claims[kBasicProfileNameKey] ||
  821. !idToken.claims[kBasicProfileGivenNameKey] ||
  822. !idToken.claims[kBasicProfileFamilyNameKey]) {
  823. return nil;
  824. }
  825. return [[GIDProfileData alloc]
  826. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  827. name:idToken.claims[kBasicProfileNameKey]
  828. givenName:idToken.claims[kBasicProfileGivenNameKey]
  829. familyName:idToken.claims[kBasicProfileFamilyNameKey]
  830. imageURL:[NSURL URLWithString:idToken.claims[kBasicProfilePictureKey]]];
  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