GIDSignIn.m 41 KB

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