GIDSignIn.m 42 KB

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