GIDSignIn.m 40 KB

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