GIDSignIn.m 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  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/GIDAuthStateMigration/GIDAuthStateMigration.h"
  21. #import "GoogleSignIn/Sources/GIDEMMSupport.h"
  22. #import "GoogleSignIn/Sources/GIDSignInInternalOptions.h"
  23. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  24. #import "GoogleSignIn/Sources/GIDCallbackQueue.h"
  25. #import "GoogleSignIn/Sources/GIDScopes.h"
  26. #import "GoogleSignIn/Sources/GIDSignInCallbackSchemes.h"
  27. #import "GoogleSignIn/Sources/GIDTokenClaimsInternalOptions.h"
  28. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  29. #import <AppCheckCore/GACAppCheckToken.h>
  30. #import "GoogleSignIn/Sources/GIDAppCheck/Implementations/GIDAppCheck.h"
  31. #import "GoogleSignIn/Sources/GIDAppCheck/UI/GIDActivityIndicatorViewController.h"
  32. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  33. #import "GoogleSignIn/Sources/GIDTimedLoader/GIDTimedLoader.h"
  34. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  35. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  36. #import "GoogleSignIn/Sources/GIDProfileData_Private.h"
  37. #import "GoogleSignIn/Sources/GIDSignInResult_Private.h"
  38. @import GTMAppAuth;
  39. #ifdef SWIFT_PACKAGE
  40. @import AppAuth;
  41. @import GTMSessionFetcherCore;
  42. #else
  43. #import <AppAuth/OIDAuthState.h>
  44. #import <AppAuth/OIDAuthorizationRequest.h>
  45. #import <AppAuth/OIDAuthorizationResponse.h>
  46. #import <AppAuth/OIDAuthorizationService.h>
  47. #import <AppAuth/OIDError.h>
  48. #import <AppAuth/OIDExternalUserAgentSession.h>
  49. #import <AppAuth/OIDIDToken.h>
  50. #import <AppAuth/OIDResponseTypes.h>
  51. #import <AppAuth/OIDServiceConfiguration.h>
  52. #import <AppAuth/OIDTokenRequest.h>
  53. #import <AppAuth/OIDTokenResponse.h>
  54. #import <AppAuth/OIDURLQueryComponent.h>
  55. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  56. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  57. #import <AppAuth/OIDAuthorizationService+IOS.h>
  58. #elif TARGET_OS_OSX
  59. #import <AppAuth/OIDAuthorizationService+Mac.h>
  60. #endif
  61. #endif
  62. NS_ASSUME_NONNULL_BEGIN
  63. // The name of the query parameter used for logging the restart of auth from EMM callback.
  64. static NSString *const kEMMRestartAuthParameter = @"emmres";
  65. // The URL template for the authorization endpoint.
  66. static NSString *const kAuthorizationURLTemplate = @"https://%@/o/oauth2/v2/auth";
  67. // The URL template for the token endpoint.
  68. static NSString *const kTokenURLTemplate = @"https://%@/token";
  69. // The URL template for the URL to get user info.
  70. static NSString *const kUserInfoURLTemplate = @"https://%@/oauth2/v3/userinfo?access_token=%@";
  71. // The URL template for the URL to revoke the token.
  72. static NSString *const kRevokeTokenURLTemplate = @"https://%@/o/oauth2/revoke?token=%@";
  73. // Expected path in the URL scheme to be handled.
  74. static NSString *const kBrowserCallbackPath = @"/oauth2callback";
  75. // Expected path for EMM callback.
  76. static NSString *const kEMMCallbackPath = @"/emmcallback";
  77. // The EMM support version
  78. static NSString *const kEMMVersion = @"1";
  79. // The error code for Google Identity.
  80. NSErrorDomain const kGIDSignInErrorDomain = @"com.google.GIDSignIn";
  81. // Keychain constants for saving state in the authentication flow.
  82. static NSString *const kGTMAppAuthKeychainName = @"auth";
  83. // Basic profile (Fat ID Token / userinfo endpoint) keys
  84. static NSString *const kBasicProfileEmailKey = @"email";
  85. static NSString *const kBasicProfilePictureKey = @"picture";
  86. static NSString *const kBasicProfileNameKey = @"name";
  87. static NSString *const kBasicProfileGivenNameKey = @"given_name";
  88. static NSString *const kBasicProfileFamilyNameKey = @"family_name";
  89. // Parameters in the callback URL coming back from browser.
  90. static NSString *const kAuthorizationCodeKeyName = @"code";
  91. static NSString *const kOAuth2ErrorKeyName = @"error";
  92. static NSString *const kOAuth2AccessDenied = @"access_denied";
  93. static NSString *const kEMMPasscodeInfoRequiredKeyName = @"emm_passcode_info_required";
  94. // Error string for unavailable keychain.
  95. static NSString *const kKeychainError = @"keychain error";
  96. // Error string for user cancelations.
  97. static NSString *const kUserCanceledError = @"The user canceled the sign-in flow.";
  98. // User preference key to detect fresh install of the app.
  99. static NSString *const kAppHasRunBeforeKey = @"GID_AppHasRunBefore";
  100. // Maximum retry interval in seconds for the fetcher.
  101. static const NSTimeInterval kFetcherMaxRetryInterval = 15.0;
  102. // The delay before the new sign-in flow can be presented after the existing one is cancelled.
  103. static const NSTimeInterval kPresentationDelayAfterCancel = 1.0;
  104. // Parameters for the auth and token exchange endpoints.
  105. static NSString *const kAudienceParameter = @"audience";
  106. // See b/11669751 .
  107. static NSString *const kOpenIDRealmParameter = @"openid.realm";
  108. static NSString *const kIncludeGrantedScopesParameter = @"include_granted_scopes";
  109. static NSString *const kLoginHintParameter = @"login_hint";
  110. static NSString *const kHostedDomainParameter = @"hd";
  111. // Parameter for requesting the token claims.
  112. static NSString *const kTokenClaimsParameter = @"claims";
  113. // Parameters for auth and token exchange endpoints using App Attest.
  114. static NSString *const kClientAssertionParameter = @"client_assertion";
  115. static NSString *const kClientAssertionTypeParameter = @"client_assertion_type";
  116. static NSString *const kClientAssertionTypeParameterValue =
  117. @"urn:ietf:params:oauth:client-assertion-type:appcheck";
  118. // Minimum time to expiration for a restored access token.
  119. static const NSTimeInterval kMinimumRestoredAccessTokenTimeToExpire = 600.0;
  120. // Info.plist config keys
  121. static NSString *const kConfigClientIDKey = @"GIDClientID";
  122. static NSString *const kConfigServerClientIDKey = @"GIDServerClientID";
  123. static NSString *const kConfigHostedDomainKey = @"GIDHostedDomain";
  124. static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
  125. // The callback queue used for authentication flow.
  126. @interface GIDAuthFlow : GIDCallbackQueue
  127. @property(nonatomic, strong, nullable) OIDAuthState *authState;
  128. @property(nonatomic, strong, nullable) NSError *error;
  129. @property(nonatomic, copy, nullable) NSString *emmSupport;
  130. @property(nonatomic, nullable) GIDProfileData *profileData;
  131. @end
  132. @implementation GIDAuthFlow
  133. @end
  134. @implementation GIDSignIn {
  135. // This value is used when sign-in flows are resumed via the handling of a URL. Its value is
  136. // set when a sign-in flow is begun via |signInWithOptions:| when the options passed don't
  137. // represent a sign in continuation.
  138. GIDSignInInternalOptions *_currentOptions;
  139. GIDTokenClaimsInternalOptions *_tokenClaimsInternalOptions;
  140. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  141. GIDAppCheck *_appCheck API_AVAILABLE(ios(14));
  142. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  143. // AppAuth configuration object.
  144. OIDServiceConfiguration *_appAuthConfiguration;
  145. // AppAuth external user-agent session state.
  146. id<OIDExternalUserAgentSession> _currentAuthorizationFlow;
  147. // Flag to indicate that the auth flow is restarting.
  148. BOOL _restarting;
  149. // Keychain manager for GTMAppAuth
  150. GTMKeychainStore *_keychainStore;
  151. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  152. // The class used to manage presenting the loading screen for fetching app check tokens.
  153. GIDTimedLoader *_timedLoader;
  154. // Flag indicating developer's intent to use App Check.
  155. BOOL _configureAppCheckCalled;
  156. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  157. }
  158. #pragma mark - Public methods
  159. // Handles the custom scheme URL opened by SFSafariViewController or the Device Policy App.
  160. //
  161. // For SFSafariViewController invoked via AppAuth, this method is used on iOS 10.
  162. // For the Device Policy App (EMM flow) this method is used on all iOS versions.
  163. - (BOOL)handleURL:(NSURL *)url {
  164. // Check if the callback path matches the expected one for a URL from Safari/Chrome/SafariVC.
  165. if ([url.path isEqual:kBrowserCallbackPath]) {
  166. if ([_currentAuthorizationFlow resumeExternalUserAgentFlowWithURL:url]) {
  167. _currentAuthorizationFlow = nil;
  168. return YES;
  169. }
  170. return NO;
  171. }
  172. // Check if the callback path matches the expected one for a URL from Google Device Policy app.
  173. if ([url.path isEqual:kEMMCallbackPath]) {
  174. return [self handleDevicePolicyAppURL:url];
  175. }
  176. return NO;
  177. }
  178. - (BOOL)hasPreviousSignIn {
  179. if ([_currentUser.authState isAuthorized]) {
  180. return YES;
  181. }
  182. OIDAuthState *authState = [self loadAuthState];
  183. return [authState isAuthorized];
  184. }
  185. - (void)restorePreviousSignInWithCompletion:(nullable void (^)(GIDGoogleUser *_Nullable user,
  186. NSError *_Nullable error))completion {
  187. [self signInWithOptions:[GIDSignInInternalOptions silentOptionsWithCompletion:
  188. ^(GIDSignInResult *signInResult, NSError *error) {
  189. if (!completion) {
  190. return;
  191. }
  192. if (signInResult) {
  193. completion(signInResult.user, nil);
  194. } else {
  195. completion(nil, error);
  196. }
  197. }]];
  198. }
  199. - (BOOL)restorePreviousSignInNoRefresh {
  200. if (_currentUser) {
  201. return YES;
  202. }
  203. // Try retrieving an authorization object from the keychain.
  204. OIDAuthState *authState = [self loadAuthState];
  205. if (!authState) {
  206. return NO;
  207. }
  208. // Restore current user without refreshing the access token.
  209. OIDIDToken *idToken =
  210. [[OIDIDToken alloc] initWithIDTokenString:authState.lastTokenResponse.idToken];
  211. GIDProfileData *profileData = [self profileDataWithIDToken:idToken];
  212. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState profileData:profileData];
  213. self.currentUser = user;
  214. return YES;
  215. }
  216. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  217. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  218. hint:(nullable NSString *)hint
  219. completion:(nullable GIDSignInCompletion)completion {
  220. GIDSignInInternalOptions *options =
  221. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  222. presentingViewController:presentingViewController
  223. loginHint:hint
  224. addScopesFlow:NO
  225. completion:completion];
  226. [self signInWithOptions:options];
  227. }
  228. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  229. hint:(nullable NSString *)hint
  230. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  231. completion:(nullable GIDSignInCompletion)completion {
  232. [self signInWithPresentingViewController:presentingViewController
  233. hint:hint
  234. additionalScopes:additionalScopes
  235. nonce:nil
  236. completion:completion];
  237. }
  238. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  239. hint:(nullable NSString *)hint
  240. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  241. nonce:(nullable NSString *)nonce
  242. completion:(nullable GIDSignInCompletion)completion {
  243. [self signInWithPresentingViewController:presentingViewController
  244. hint:hint
  245. additionalScopes:additionalScopes
  246. nonce:nonce
  247. tokenClaims:nil
  248. completion:completion];
  249. }
  250. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  251. tokenClaims:(nullable NSSet<GIDTokenClaim *> *)tokenClaims
  252. completion:(nullable GIDSignInCompletion)completion {
  253. [self signInWithPresentingViewController:presentingViewController
  254. hint:nil
  255. tokenClaims:tokenClaims
  256. completion:completion];
  257. }
  258. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  259. hint:(nullable NSString *)hint
  260. tokenClaims:(nullable NSSet<GIDTokenClaim *> *)tokenClaims
  261. completion:(nullable GIDSignInCompletion)completion {
  262. [self signInWithPresentingViewController:presentingViewController
  263. hint:hint
  264. additionalScopes:@[]
  265. tokenClaims:tokenClaims
  266. completion:completion];
  267. }
  268. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  269. hint:(nullable NSString *)hint
  270. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  271. tokenClaims:(nullable NSSet<GIDTokenClaim *> *)tokenClaims
  272. completion:(nullable GIDSignInCompletion)completion {
  273. [self signInWithPresentingViewController:presentingViewController
  274. hint:hint
  275. additionalScopes:additionalScopes
  276. nonce:nil
  277. tokenClaims:tokenClaims
  278. completion:completion];
  279. }
  280. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  281. hint:(nullable NSString *)hint
  282. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  283. nonce:(nullable NSString *)nonce
  284. tokenClaims:(nullable NSSet<GIDTokenClaim *> *)tokenClaims
  285. completion:(nullable GIDSignInCompletion)completion {
  286. GIDSignInInternalOptions *options =
  287. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  288. presentingViewController:presentingViewController
  289. loginHint:hint
  290. addScopesFlow:NO
  291. scopes:additionalScopes
  292. nonce:nonce
  293. tokenClaims:tokenClaims
  294. completion:completion];
  295. [self signInWithOptions:options];
  296. }
  297. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  298. completion:(nullable GIDSignInCompletion)completion {
  299. [self signInWithPresentingViewController:presentingViewController
  300. hint:nil
  301. completion:completion];
  302. }
  303. - (void)addScopes:(NSArray<NSString *> *)scopes
  304. presentingViewController:(UIViewController *)presentingViewController
  305. completion:(nullable GIDSignInCompletion)completion {
  306. GIDConfiguration *configuration = self.currentUser.configuration;
  307. GIDSignInInternalOptions *options =
  308. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  309. presentingViewController:presentingViewController
  310. loginHint:self.currentUser.profile.email
  311. addScopesFlow:YES
  312. completion:completion];
  313. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  314. NSMutableSet<NSString *> *grantedScopes =
  315. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  316. // Check to see if all requested scopes have already been granted.
  317. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  318. // All requested scopes have already been granted, notify callback of failure.
  319. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  320. code:kGIDSignInErrorCodeScopesAlreadyGranted
  321. userInfo:nil];
  322. if (completion) {
  323. dispatch_async(dispatch_get_main_queue(), ^{
  324. completion(nil, error);
  325. });
  326. }
  327. return;
  328. }
  329. // Use the union of granted and requested scopes.
  330. [grantedScopes unionSet:requestedScopes];
  331. options.scopes = [grantedScopes allObjects];
  332. [self signInWithOptions:options];
  333. }
  334. #elif TARGET_OS_OSX
  335. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  336. hint:(nullable NSString *)hint
  337. completion:(nullable GIDSignInCompletion)completion {
  338. GIDSignInInternalOptions *options =
  339. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  340. presentingWindow:presentingWindow
  341. loginHint:hint
  342. addScopesFlow:NO
  343. completion:completion];
  344. [self signInWithOptions:options];
  345. }
  346. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  347. completion:(nullable GIDSignInCompletion)completion {
  348. [self signInWithPresentingWindow:presentingWindow
  349. hint:nil
  350. completion:completion];
  351. }
  352. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  353. hint:(nullable NSString *)hint
  354. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  355. completion:(nullable GIDSignInCompletion)completion {
  356. [self signInWithPresentingWindow:presentingWindow
  357. hint:hint
  358. additionalScopes:additionalScopes
  359. nonce:nil
  360. completion:completion];
  361. }
  362. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  363. hint:(nullable NSString *)hint
  364. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  365. nonce:(nullable NSString *)nonce
  366. completion:(nullable GIDSignInCompletion)completion {
  367. [self signInWithPresentingWindow:presentingWindow
  368. hint:hint
  369. additionalScopes:additionalScopes
  370. nonce:nonce
  371. tokenClaims:nil
  372. completion:completion];
  373. }
  374. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  375. tokenClaims:(nullable NSSet<GIDTokenClaim *> *)tokenClaims
  376. completion:(nullable GIDSignInCompletion)completion {
  377. [self signInWithPresentingWindow:presentingWindow
  378. hint:nil
  379. tokenClaims:tokenClaims
  380. completion:completion];
  381. }
  382. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  383. hint:(nullable NSString *)hint
  384. tokenClaims:(nullable NSSet<GIDTokenClaim *> *)tokenClaims
  385. completion:(nullable GIDSignInCompletion)completion {
  386. [self signInWithPresentingWindow:presentingWindow
  387. hint:hint
  388. additionalScopes:@[]
  389. tokenClaims:tokenClaims
  390. completion:completion];
  391. }
  392. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  393. hint:(nullable NSString *)hint
  394. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  395. tokenClaims:(nullable NSSet<GIDTokenClaim *> *)tokenClaims
  396. completion:(nullable GIDSignInCompletion)completion {
  397. [self signInWithPresentingWindow:presentingWindow
  398. hint:hint
  399. additionalScopes:additionalScopes
  400. nonce:nil
  401. tokenClaims:tokenClaims
  402. completion:completion];
  403. }
  404. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  405. hint:(nullable NSString *)hint
  406. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  407. nonce:(nullable NSString *)nonce
  408. tokenClaims:(nullable NSSet<GIDTokenClaim *> *)tokenClaims
  409. completion:(nullable GIDSignInCompletion)completion {
  410. GIDSignInInternalOptions *options =
  411. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  412. presentingWindow:presentingWindow
  413. loginHint:hint
  414. addScopesFlow:NO
  415. scopes:additionalScopes
  416. nonce:nonce
  417. tokenClaims:tokenClaims
  418. completion:completion];
  419. [self signInWithOptions:options];
  420. }
  421. - (void)addScopes:(NSArray<NSString *> *)scopes
  422. presentingWindow:(NSWindow *)presentingWindow
  423. completion:(nullable GIDSignInCompletion)completion {
  424. GIDConfiguration *configuration = self.currentUser.configuration;
  425. GIDSignInInternalOptions *options =
  426. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  427. presentingWindow:presentingWindow
  428. loginHint:self.currentUser.profile.email
  429. addScopesFlow:YES
  430. completion:completion];
  431. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  432. NSMutableSet<NSString *> *grantedScopes =
  433. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  434. // Check to see if all requested scopes have already been granted.
  435. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  436. // All requested scopes have already been granted, notify callback of failure.
  437. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  438. code:kGIDSignInErrorCodeScopesAlreadyGranted
  439. userInfo:nil];
  440. if (completion) {
  441. dispatch_async(dispatch_get_main_queue(), ^{
  442. completion(nil, error);
  443. });
  444. }
  445. return;
  446. }
  447. // Use the union of granted and requested scopes.
  448. [grantedScopes unionSet:requestedScopes];
  449. options.scopes = [grantedScopes allObjects];
  450. [self signInWithOptions:options];
  451. }
  452. #endif // TARGET_OS_OSX
  453. - (void)signOut {
  454. // Clear the current user if there is one.
  455. if (_currentUser) {
  456. self.currentUser = nil;
  457. }
  458. // Remove all state from the keychain.
  459. [self removeAllKeychainEntries];
  460. }
  461. - (void)disconnectWithCompletion:(nullable GIDDisconnectCompletion)completion {
  462. OIDAuthState *authState = _currentUser.authState;
  463. if (!authState) {
  464. // Even the user is not signed in right now, we still need to remove any token saved in the
  465. // keychain.
  466. authState = [self loadAuthState];
  467. }
  468. // Either access or refresh token would work, but we won't have access token if the auth is
  469. // retrieved from keychain.
  470. NSString *token = authState.lastTokenResponse.accessToken;
  471. if (!token) {
  472. token = authState.lastTokenResponse.refreshToken;
  473. }
  474. if (!token) {
  475. [self signOut];
  476. // Nothing to do here, consider the operation successful.
  477. if (completion) {
  478. dispatch_async(dispatch_get_main_queue(), ^{
  479. completion(nil);
  480. });
  481. }
  482. return;
  483. }
  484. NSString *revokeURLString = [NSString stringWithFormat:kRevokeTokenURLTemplate,
  485. [GIDSignInPreferences googleAuthorizationServer], token];
  486. // Append logging parameter
  487. revokeURLString = [NSString stringWithFormat:@"%@&%@=%@&%@=%@",
  488. revokeURLString,
  489. kSDKVersionLoggingParameter,
  490. GIDVersion(),
  491. kEnvironmentLoggingParameter,
  492. GIDEnvironment()];
  493. NSURL *revokeURL = [NSURL URLWithString:revokeURLString];
  494. [self startFetchURL:revokeURL
  495. fromAuthState:authState
  496. withComment:@"GIDSignIn: revoke tokens"
  497. withCompletionHandler:^(NSData *data, NSError *error) {
  498. // Revoking an already revoked token seems always successful, which helps us here.
  499. if (!error) {
  500. [self signOut];
  501. }
  502. if (completion) {
  503. dispatch_async(dispatch_get_main_queue(), ^{
  504. completion(error);
  505. });
  506. }
  507. }];
  508. }
  509. #pragma mark - Custom getters and setters
  510. + (GIDSignIn *)sharedInstance {
  511. static dispatch_once_t once;
  512. static GIDSignIn *sharedInstance;
  513. dispatch_once(&once, ^{
  514. GTMKeychainStore *keychainStore =
  515. [[GTMKeychainStore alloc] initWithItemName:kGTMAppAuthKeychainName];
  516. GIDAuthStateMigration *authStateMigrationService =
  517. [[GIDAuthStateMigration alloc] initWithKeychainStore:keychainStore];
  518. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  519. if (@available(iOS 14.0, *)) {
  520. GIDAppCheck *appCheck = [GIDAppCheck appCheckUsingAppAttestProvider];
  521. sharedInstance = [[self alloc] initWithKeychainStore:keychainStore
  522. authStateMigrationService:authStateMigrationService
  523. appCheck:appCheck];
  524. }
  525. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  526. if (!sharedInstance) {
  527. sharedInstance = [[self alloc] initWithKeychainStore:keychainStore
  528. authStateMigrationService:authStateMigrationService];
  529. }
  530. });
  531. return sharedInstance;
  532. }
  533. #pragma mark - Configuring and pre-warming
  534. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  535. - (void)configureWithCompletion:(nullable void (^)(NSError * _Nullable))completion {
  536. @synchronized(self) {
  537. _configureAppCheckCalled = YES;
  538. [_appCheck prepareForAppCheckWithCompletion:^(NSError * _Nullable error) {
  539. if (completion) {
  540. completion(error);
  541. }
  542. }];
  543. }
  544. }
  545. - (void)configureDebugProviderWithAPIKey:(NSString *)APIKey
  546. completion:(nullable void (^)(NSError * _Nullable))completion {
  547. @synchronized(self) {
  548. _appCheck = [GIDAppCheck appCheckUsingDebugProviderWithAPIKey:APIKey];
  549. [_appCheck prepareForAppCheckWithCompletion:^(NSError * _Nullable error) {
  550. if (completion) {
  551. completion(error);
  552. }
  553. }];
  554. }
  555. }
  556. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  557. #pragma mark - Private methods
  558. - (instancetype)initWithKeychainStore:(GTMKeychainStore *)keychainStore
  559. authStateMigrationService:(GIDAuthStateMigration *)authStateMigrationService {
  560. self = [super init];
  561. if (self) {
  562. _keychainStore = keychainStore;
  563. _tokenClaimsInternalOptions = [[GIDTokenClaimsInternalOptions alloc] init];
  564. // Get the bundle of the current executable.
  565. NSBundle *bundle = NSBundle.mainBundle;
  566. // If we have a bundle, try to set the active configuration from the bundle's Info.plist.
  567. if (bundle) {
  568. _configuration = [GIDSignIn configurationFromBundle:bundle];
  569. }
  570. // Check to see if the 3P app is being run for the first time after a fresh install.
  571. BOOL isFreshInstall = [self isFreshInstall];
  572. NSString *authorizationEnpointURL = [NSString stringWithFormat:kAuthorizationURLTemplate,
  573. [GIDSignInPreferences googleAuthorizationServer]];
  574. NSString *tokenEndpointURL = [NSString stringWithFormat:kTokenURLTemplate,
  575. [GIDSignInPreferences googleTokenServer]];
  576. _appAuthConfiguration = [[OIDServiceConfiguration alloc]
  577. initWithAuthorizationEndpoint:[NSURL URLWithString:authorizationEnpointURL]
  578. tokenEndpoint:[NSURL URLWithString:tokenEndpointURL]];
  579. // Perform migration of auth state from old versions of the SDK if needed.
  580. [authStateMigrationService migrateIfNeededWithTokenURL:_appAuthConfiguration.tokenEndpoint
  581. callbackPath:kBrowserCallbackPath
  582. isFreshInstall:isFreshInstall];
  583. }
  584. return self;
  585. }
  586. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  587. - (instancetype)initWithKeychainStore:(GTMKeychainStore *)keychainStore
  588. authStateMigrationService:(GIDAuthStateMigration *)authStateMigrationService
  589. appCheck:(GIDAppCheck *)appCheck {
  590. self = [self initWithKeychainStore:keychainStore
  591. authStateMigrationService:authStateMigrationService];
  592. if (self) {
  593. _appCheck = appCheck;
  594. _configureAppCheckCalled = NO;
  595. }
  596. return self;
  597. }
  598. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  599. // Does sanity check for parameters and then authenticates if necessary.
  600. - (void)signInWithOptions:(GIDSignInInternalOptions *)options {
  601. // Options for continuation are not the options we want to cache. The purpose of caching the
  602. // options in the first place is to provide continuation flows with a starting place from which to
  603. // derive suitable options for the continuation!
  604. if (!options.continuation) {
  605. _currentOptions = options;
  606. }
  607. if (options.interactive) {
  608. // Ensure that a configuration has been provided.
  609. if (!_configuration) {
  610. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  611. [NSException raise:NSInvalidArgumentException
  612. format:@"No active configuration. Make sure GIDClientID is set in Info.plist."];
  613. return;
  614. }
  615. // Explicitly throw exception for missing client ID here. This must come before
  616. // scheme check because schemes rely on reverse client IDs.
  617. [self assertValidParameters];
  618. [self assertValidPresentingViewController];
  619. // If the application does not support the required URL schemes tell the developer so.
  620. GIDSignInCallbackSchemes *schemes =
  621. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  622. NSArray<NSString *> *unsupportedSchemes = [schemes unsupportedSchemes];
  623. if (unsupportedSchemes.count != 0) {
  624. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  625. [NSException raise:NSInvalidArgumentException
  626. format:@"Your app is missing support for the following URL schemes: %@",
  627. [unsupportedSchemes componentsJoinedByString:@", "]];
  628. }
  629. }
  630. // If this is a non-interactive flow, use cached authentication if possible.
  631. if (!options.interactive && _currentUser) {
  632. [_currentUser refreshTokensIfNeededWithCompletion:^(GIDGoogleUser *unused, NSError *error) {
  633. if (error) {
  634. [self authenticateWithOptions:options];
  635. } else {
  636. if (options.completion) {
  637. self->_currentOptions = nil;
  638. dispatch_async(dispatch_get_main_queue(), ^{
  639. GIDSignInResult *signInResult =
  640. [[GIDSignInResult alloc] initWithGoogleUser:self->_currentUser serverAuthCode:nil];
  641. options.completion(signInResult, nil);
  642. });
  643. }
  644. }
  645. }];
  646. } else {
  647. NSError *claimsError;
  648. // If tokenClaims are invalid or JSON serialization fails, return with an error.
  649. options.tokenClaimsAsJSON = [_tokenClaimsInternalOptions
  650. validatedJSONStringForClaims:options.tokenClaims
  651. error:&claimsError];
  652. if (claimsError) {
  653. if (options.completion) {
  654. self->_currentOptions = nil;
  655. dispatch_async(dispatch_get_main_queue(), ^{
  656. options.completion(nil, claimsError);
  657. });
  658. }
  659. return;
  660. }
  661. [self authenticateWithOptions:options];
  662. }
  663. }
  664. #pragma mark - Authentication flow
  665. - (void)authenticateInteractivelyWithOptions:(GIDSignInInternalOptions *)options {
  666. NSString *emmSupport;
  667. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  668. emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  669. #elif TARGET_OS_MACCATALYST || TARGET_OS_OSX
  670. emmSupport = nil;
  671. #endif // TARGET_OS_MACCATALYST || TARGET_OS_OSX
  672. [self authorizationRequestWithOptions:options
  673. completion:^(OIDAuthorizationRequest * _Nullable request,
  674. NSError * _Nullable error) {
  675. self->_currentAuthorizationFlow =
  676. [OIDAuthorizationService presentAuthorizationRequest:request
  677. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  678. presentingViewController:options.presentingViewController
  679. #elif TARGET_OS_OSX
  680. presentingWindow:options.presentingWindow
  681. #endif // TARGET_OS_OSX
  682. callback:
  683. ^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  684. NSError *_Nullable error) {
  685. [self processAuthorizationResponse:authorizationResponse
  686. error:error
  687. emmSupport:emmSupport];
  688. }];
  689. }];
  690. }
  691. - (void)authorizationRequestWithOptions:(GIDSignInInternalOptions *)options completion:
  692. (void (^)(OIDAuthorizationRequest *_Nullable request, NSError *_Nullable error))completion {
  693. BOOL shouldCreateAuthRequest = YES;
  694. NSMutableDictionary<NSString *, NSString *> *additionalParameters =
  695. [self additionalParametersFromOptions:options];
  696. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  697. if (@available(iOS 14.0, *)) {
  698. // Only use `_appCheck` (created via singleton `+[GIDSignIn sharedInstance]` call) if
  699. // `GIDAppCheck` has been successfully prepared OR if the developer has attempted to configure.
  700. // If former is false and the latter true, then preparation step failed for some reason; we
  701. // still want to try to pass along the app check token (it just may take longer since the
  702. // pre-warm step failed).
  703. if ([_appCheck isPrepared] || _configureAppCheckCalled) {
  704. shouldCreateAuthRequest = NO;
  705. UIViewController *presentingVC = options.presentingViewController;
  706. if (!_timedLoader) {
  707. _timedLoader = [[GIDTimedLoader alloc] initWithPresentingViewController:presentingVC];
  708. }
  709. [_timedLoader startTiming];
  710. [self->_appCheck getLimitedUseTokenWithCompletion:^(GACAppCheckToken * _Nullable token,
  711. NSError * _Nullable error) {
  712. if (token) {
  713. additionalParameters[kClientAssertionTypeParameter] = kClientAssertionTypeParameterValue;
  714. additionalParameters[kClientAssertionParameter] = token.token;
  715. }
  716. #if DEBUG
  717. if (error) {
  718. NSLog(@"[Google Sign-In iOS]: Error retrieving App Check limited use token: %@", error);
  719. }
  720. #endif
  721. OIDAuthorizationRequest *request = [self authorizationRequestWithOptions:options
  722. additionalParameters:additionalParameters];
  723. if (self->_timedLoader.animationStatus == GIDTimedLoaderAnimationStatusAnimating) {
  724. [self->_timedLoader stopTimingWithCompletion:^{
  725. completion(request, error);
  726. }];
  727. } else {
  728. completion(request, error);
  729. }
  730. }];
  731. }
  732. }
  733. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  734. if (shouldCreateAuthRequest) {
  735. OIDAuthorizationRequest *request = [self authorizationRequestWithOptions:options
  736. additionalParameters:additionalParameters];
  737. completion(request, nil);
  738. }
  739. }
  740. - (OIDAuthorizationRequest *)
  741. authorizationRequestWithOptions:(GIDSignInInternalOptions *)options
  742. additionalParameters:(NSDictionary<NSString *, NSString *> *)additionalParameters {
  743. OIDAuthorizationRequest *request;
  744. if (options.nonce) {
  745. request = [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  746. clientId:options.configuration.clientID
  747. scopes:options.scopes
  748. redirectURL:[self redirectURLWithOptions:options]
  749. responseType:OIDResponseTypeCode
  750. nonce:options.nonce
  751. additionalParameters:additionalParameters];
  752. } else {
  753. request = [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  754. clientId:options.configuration.clientID
  755. scopes:options.scopes
  756. redirectURL:[self redirectURLWithOptions:options]
  757. responseType:OIDResponseTypeCode
  758. additionalParameters:additionalParameters];
  759. }
  760. return request;
  761. }
  762. - (NSMutableDictionary<NSString *, NSString *> *)
  763. additionalParametersFromOptions:(GIDSignInInternalOptions *)options {
  764. NSString *emmSupport;
  765. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  766. emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  767. #elif TARGET_OS_MACCATALYST || TARGET_OS_OSX
  768. emmSupport = nil;
  769. #endif // TARGET_OS_MACCATALYST || TARGET_OS_OSX
  770. NSMutableDictionary<NSString *, NSString *> *additionalParameters =
  771. [[NSMutableDictionary alloc] init];
  772. additionalParameters[kIncludeGrantedScopesParameter] = @"true";
  773. if (options.configuration.serverClientID) {
  774. additionalParameters[kAudienceParameter] = options.configuration.serverClientID;
  775. }
  776. if (options.loginHint) {
  777. additionalParameters[kLoginHintParameter] = options.loginHint;
  778. }
  779. if (options.configuration.hostedDomain) {
  780. additionalParameters[kHostedDomainParameter] = options.configuration.hostedDomain;
  781. }
  782. if (options.tokenClaimsAsJSON) {
  783. additionalParameters[kTokenClaimsParameter] = options.tokenClaimsAsJSON;
  784. }
  785. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  786. [additionalParameters addEntriesFromDictionary:
  787. [GIDEMMSupport parametersWithParameters:options.extraParams
  788. emmSupport:emmSupport
  789. isPasscodeInfoRequired:NO]];
  790. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  791. [additionalParameters addEntriesFromDictionary:options.extraParams];
  792. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  793. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  794. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  795. return additionalParameters;
  796. }
  797. - (NSURL *)redirectURLWithOptions:(GIDSignInInternalOptions *)options {
  798. GIDSignInCallbackSchemes *schemes =
  799. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  800. NSURL *redirectURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@:%@",
  801. [schemes clientIdentifierScheme],
  802. kBrowserCallbackPath]];
  803. return redirectURL;
  804. }
  805. - (void)processAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse
  806. error:(NSError *)error
  807. emmSupport:(NSString *)emmSupport {
  808. if (_restarting) {
  809. // The auth flow is restarting, so the work here would be performed in the next round.
  810. _restarting = NO;
  811. return;
  812. }
  813. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  814. authFlow.emmSupport = emmSupport;
  815. if (authorizationResponse) {
  816. if (authorizationResponse.authorizationCode.length) {
  817. authFlow.authState = [[OIDAuthState alloc]
  818. initWithAuthorizationResponse:authorizationResponse];
  819. // perform auth code exchange
  820. [self maybeFetchToken:authFlow];
  821. } else {
  822. // There was a failure, convert to appropriate error code.
  823. NSString *errorString;
  824. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  825. NSDictionary<NSString *, NSObject *> *params = authorizationResponse.additionalParameters;
  826. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  827. if (authFlow.emmSupport) {
  828. [authFlow wait];
  829. BOOL isEMMError = [[GIDEMMErrorHandler sharedInstance]
  830. handleErrorFromResponse:params
  831. completion:^{
  832. [authFlow next];
  833. }];
  834. if (isEMMError) {
  835. errorCode = kGIDSignInErrorCodeEMM;
  836. }
  837. }
  838. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  839. errorString = (NSString *)params[kOAuth2ErrorKeyName];
  840. if ([errorString isEqualToString:kOAuth2AccessDenied]) {
  841. errorCode = kGIDSignInErrorCodeCanceled;
  842. }
  843. authFlow.error = [self errorWithString:errorString code:errorCode];
  844. }
  845. } else {
  846. NSString *errorString = [error localizedDescription];
  847. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  848. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow ||
  849. error.code == OIDErrorCodeProgramCanceledAuthorizationFlow) {
  850. // The user has canceled the flow at the iOS modal dialog.
  851. errorString = kUserCanceledError;
  852. errorCode = kGIDSignInErrorCodeCanceled;
  853. }
  854. authFlow.error = [self errorWithString:errorString code:errorCode];
  855. }
  856. [self addDecodeIdTokenCallback:authFlow];
  857. [self addSaveAuthCallback:authFlow];
  858. [self addCompletionCallback:authFlow];
  859. }
  860. // Perform authentication with the provided options.
  861. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options {
  862. // If this is an interactive flow, we're not going to try to restore any saved auth state.
  863. if (options.interactive) {
  864. [self authenticateInteractivelyWithOptions:options];
  865. return;
  866. }
  867. // Try retrieving an authorization object from the keychain.
  868. OIDAuthState *authState = [self loadAuthState];
  869. if (![authState isAuthorized]) {
  870. // No valid auth in keychain, per documentation/spec, notify callback of failure.
  871. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  872. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  873. userInfo:nil];
  874. if (options.completion) {
  875. _currentOptions = nil;
  876. dispatch_async(dispatch_get_main_queue(), ^{
  877. options.completion(nil, error);
  878. });
  879. }
  880. return;
  881. }
  882. // Complete the auth flow using saved auth in keychain.
  883. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  884. authFlow.authState = authState;
  885. [self maybeFetchToken:authFlow];
  886. [self addDecodeIdTokenCallback:authFlow];
  887. [self addSaveAuthCallback:authFlow];
  888. [self addCompletionCallback:authFlow];
  889. }
  890. // Fetches the access token if necessary as part of the auth flow.
  891. - (void)maybeFetchToken:(GIDAuthFlow *)authFlow {
  892. OIDAuthState *authState = authFlow.authState;
  893. // Do nothing if we have an auth flow error or a restored access token that isn't near expiration.
  894. if (authFlow.error ||
  895. (authState.lastTokenResponse.accessToken &&
  896. [authState.lastTokenResponse.accessTokenExpirationDate timeIntervalSinceNow] >
  897. kMinimumRestoredAccessTokenTimeToExpire)) {
  898. return;
  899. }
  900. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  901. if (_currentOptions.configuration.serverClientID) {
  902. additionalParameters[kAudienceParameter] = _currentOptions.configuration.serverClientID;
  903. }
  904. if (_currentOptions.configuration.openIDRealm) {
  905. additionalParameters[kOpenIDRealmParameter] = _currentOptions.configuration.openIDRealm;
  906. }
  907. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  908. NSDictionary<NSString *, NSObject *> *params =
  909. authState.lastAuthorizationResponse.additionalParameters;
  910. NSString *passcodeInfoRequired = (NSString *)params[kEMMPasscodeInfoRequiredKeyName];
  911. [additionalParameters addEntriesFromDictionary:
  912. [GIDEMMSupport parametersWithParameters:@{}
  913. emmSupport:authFlow.emmSupport
  914. isPasscodeInfoRequired:passcodeInfoRequired.length > 0]];
  915. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  916. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  917. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  918. OIDTokenRequest *tokenRequest;
  919. if (!authState.lastTokenResponse.accessToken &&
  920. authState.lastAuthorizationResponse.authorizationCode) {
  921. tokenRequest = [authState.lastAuthorizationResponse
  922. tokenExchangeRequestWithAdditionalParameters:additionalParameters];
  923. } else {
  924. [additionalParameters
  925. addEntriesFromDictionary:authState.lastTokenResponse.request.additionalParameters];
  926. tokenRequest = [authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  927. }
  928. [authFlow wait];
  929. [OIDAuthorizationService performTokenRequest:tokenRequest
  930. originalAuthorizationResponse:authFlow.authState.lastAuthorizationResponse
  931. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  932. NSError *_Nullable error) {
  933. [authState updateWithTokenResponse:tokenResponse error:error];
  934. authFlow.error = error;
  935. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  936. if (authFlow.emmSupport) {
  937. [GIDEMMSupport handleTokenFetchEMMError:error completion:^(NSError *error) {
  938. authFlow.error = error;
  939. [authFlow next];
  940. }];
  941. } else {
  942. [authFlow next];
  943. }
  944. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  945. [authFlow next];
  946. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  947. }];
  948. }
  949. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  950. - (void)addSaveAuthCallback:(GIDAuthFlow *)authFlow {
  951. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  952. [authFlow addCallback:^() {
  953. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  954. OIDAuthState *authState = handlerAuthFlow.authState;
  955. if (authState && !handlerAuthFlow.error) {
  956. if (![self saveAuthState:authState]) {
  957. handlerAuthFlow.error = [self errorWithString:kKeychainError
  958. code:kGIDSignInErrorCodeKeychain];
  959. return;
  960. }
  961. if (self->_currentOptions.addScopesFlow) {
  962. [self->_currentUser updateWithTokenResponse:authState.lastTokenResponse
  963. authorizationResponse:authState.lastAuthorizationResponse
  964. profileData:handlerAuthFlow.profileData];
  965. } else {
  966. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState
  967. profileData:handlerAuthFlow.profileData];
  968. self.currentUser = user;
  969. }
  970. }
  971. }];
  972. }
  973. // Adds a callback to the auth flow to extract user data from the ID token where available and
  974. // make a userinfo request if necessary.
  975. - (void)addDecodeIdTokenCallback:(GIDAuthFlow *)authFlow {
  976. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  977. [authFlow addCallback:^() {
  978. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  979. OIDAuthState *authState = handlerAuthFlow.authState;
  980. if (!authState || handlerAuthFlow.error) {
  981. return;
  982. }
  983. OIDIDToken *idToken =
  984. [[OIDIDToken alloc] initWithIDTokenString: authState.lastTokenResponse.idToken];
  985. // If the profile data are present in the ID token, use them.
  986. if (idToken) {
  987. handlerAuthFlow.profileData = [self profileDataWithIDToken:idToken];
  988. }
  989. // If we can't retrieve profile data from the ID token, make a userInfo request to fetch them.
  990. if (!handlerAuthFlow.profileData) {
  991. [handlerAuthFlow wait];
  992. NSURL *infoURL = [NSURL URLWithString:
  993. [NSString stringWithFormat:kUserInfoURLTemplate,
  994. [GIDSignInPreferences googleUserInfoServer],
  995. authState.lastTokenResponse.accessToken]];
  996. [self startFetchURL:infoURL
  997. fromAuthState:authState
  998. withComment:@"GIDSignIn: fetch basic profile info"
  999. withCompletionHandler:^(NSData *data, NSError *error) {
  1000. if (data && !error) {
  1001. NSError *jsonDeserializationError;
  1002. NSDictionary<NSString *, NSString *> *profileDict =
  1003. [NSJSONSerialization JSONObjectWithData:data
  1004. options:NSJSONReadingMutableContainers
  1005. error:&jsonDeserializationError];
  1006. if (profileDict) {
  1007. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  1008. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  1009. name:profileDict[kBasicProfileNameKey]
  1010. givenName:profileDict[kBasicProfileGivenNameKey]
  1011. familyName:profileDict[kBasicProfileFamilyNameKey]
  1012. imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
  1013. }
  1014. }
  1015. if (error) {
  1016. handlerAuthFlow.error = error;
  1017. }
  1018. [handlerAuthFlow next];
  1019. }];
  1020. }
  1021. }];
  1022. }
  1023. // Adds a callback to the auth flow to complete the flow by calling the sign-in callback.
  1024. - (void)addCompletionCallback:(GIDAuthFlow *)authFlow {
  1025. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  1026. [authFlow addCallback:^() {
  1027. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  1028. if (self->_currentOptions.completion) {
  1029. GIDSignInCompletion completion = self->_currentOptions.completion;
  1030. self->_currentOptions = nil;
  1031. dispatch_async(dispatch_get_main_queue(), ^{
  1032. if (handlerAuthFlow.error) {
  1033. completion(nil, handlerAuthFlow.error);
  1034. } else {
  1035. OIDAuthState *authState = handlerAuthFlow.authState;
  1036. NSString *_Nullable serverAuthCode =
  1037. [authState.lastTokenResponse.additionalParameters[@"server_code"] copy];
  1038. GIDSignInResult *signInResult =
  1039. [[GIDSignInResult alloc] initWithGoogleUser:self->_currentUser
  1040. serverAuthCode:serverAuthCode];
  1041. completion(signInResult, nil);
  1042. }
  1043. });
  1044. }
  1045. }];
  1046. }
  1047. - (void)startFetchURL:(NSURL *)URL
  1048. fromAuthState:(OIDAuthState *)authState
  1049. withComment:(NSString *)comment
  1050. withCompletionHandler:(void (^)(NSData *, NSError *))handler {
  1051. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  1052. GTMSessionFetcher *fetcher;
  1053. GTMAuthSession *authorization = [[GTMAuthSession alloc] initWithAuthState:authState];
  1054. id<GTMSessionFetcherServiceProtocol> fetcherService = authorization.fetcherService;
  1055. if (fetcherService) {
  1056. fetcher = [fetcherService fetcherWithRequest:request];
  1057. } else {
  1058. fetcher = [GTMSessionFetcher fetcherWithRequest:request];
  1059. }
  1060. fetcher.retryEnabled = YES;
  1061. fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
  1062. fetcher.comment = comment;
  1063. [fetcher beginFetchWithCompletionHandler:handler];
  1064. }
  1065. // Parse incoming URL from the Google Device Policy app.
  1066. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  1067. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  1068. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  1069. NSObject<NSCopying> *actionParam = params[@"action"];
  1070. NSString *actionString =
  1071. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  1072. if (![@"restart_auth" isEqualToString:actionString]) {
  1073. return NO;
  1074. }
  1075. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1076. if (!_currentOptions.presentingViewController) {
  1077. return NO;
  1078. }
  1079. #elif TARGET_OS_OSX
  1080. if (!_currentOptions.presentingWindow) {
  1081. return NO;
  1082. }
  1083. #endif // TARGET_OS_OSX
  1084. if (!_currentAuthorizationFlow) {
  1085. return NO;
  1086. }
  1087. _restarting = YES;
  1088. [_currentAuthorizationFlow cancel];
  1089. _currentAuthorizationFlow = nil;
  1090. _restarting = NO;
  1091. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  1092. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  1093. // so we need to wait until the previous presentation is completely gone to ensure the right
  1094. // anchor window is used here.
  1095. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  1096. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  1097. dispatch_get_main_queue(), ^{
  1098. [self signInWithOptions:[self->_currentOptions optionsWithExtraParameters:extraParameters
  1099. forContinuation:YES]];
  1100. });
  1101. return YES;
  1102. }
  1103. #pragma mark - Helpers
  1104. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  1105. if (errorString == nil) {
  1106. errorString = @"Unknown error";
  1107. }
  1108. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  1109. return [NSError errorWithDomain:kGIDSignInErrorDomain
  1110. code:code
  1111. userInfo:errorDict];
  1112. }
  1113. + (BOOL)isOperatingSystemAtLeast9 {
  1114. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  1115. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  1116. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  1117. }
  1118. // Asserts the parameters being valid.
  1119. - (void)assertValidParameters {
  1120. if (![_currentOptions.configuration.clientID length]) {
  1121. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  1122. [NSException raise:NSInvalidArgumentException
  1123. format:@"You must specify |clientID| in |GIDConfiguration|"];
  1124. }
  1125. }
  1126. // Assert that the presenting view controller has been set.
  1127. - (void)assertValidPresentingViewController {
  1128. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1129. if (!_currentOptions.presentingViewController)
  1130. #elif TARGET_OS_OSX
  1131. if (!_currentOptions.presentingWindow)
  1132. #endif // TARGET_OS_OSX
  1133. {
  1134. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  1135. [NSException raise:NSInvalidArgumentException
  1136. format:@"|presentingViewController| must be set."];
  1137. }
  1138. }
  1139. // Checks whether or not this is the first time the app runs.
  1140. - (BOOL)isFreshInstall {
  1141. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  1142. if ([defaults boolForKey:kAppHasRunBeforeKey]) {
  1143. return NO;
  1144. }
  1145. [defaults setBool:YES forKey:kAppHasRunBeforeKey];
  1146. return YES;
  1147. }
  1148. - (void)removeAllKeychainEntries {
  1149. [_keychainStore removeAuthSessionWithError:nil];
  1150. }
  1151. - (BOOL)saveAuthState:(OIDAuthState *)authState {
  1152. GTMAuthSession *authorization = [[GTMAuthSession alloc] initWithAuthState:authState];
  1153. NSError *error;
  1154. [_keychainStore saveAuthSession:authorization error:&error];
  1155. return error == nil;
  1156. }
  1157. - (OIDAuthState *)loadAuthState {
  1158. GTMAuthSession *authorization = [_keychainStore retrieveAuthSessionWithError:nil];
  1159. return authorization.authState;
  1160. }
  1161. // Generates user profile from OIDIDToken.
  1162. - (GIDProfileData *)profileDataWithIDToken:(OIDIDToken *)idToken {
  1163. if (!idToken ||
  1164. !idToken.claims[kBasicProfilePictureKey] ||
  1165. !idToken.claims[kBasicProfileNameKey] ||
  1166. !idToken.claims[kBasicProfileGivenNameKey] ||
  1167. !idToken.claims[kBasicProfileFamilyNameKey]) {
  1168. return nil;
  1169. }
  1170. return [[GIDProfileData alloc]
  1171. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  1172. name:idToken.claims[kBasicProfileNameKey]
  1173. givenName:idToken.claims[kBasicProfileGivenNameKey]
  1174. familyName:idToken.claims[kBasicProfileFamilyNameKey]
  1175. imageURL:[NSURL URLWithString:idToken.claims[kBasicProfilePictureKey]]];
  1176. }
  1177. // Try to retrieve a configuration value from an |NSBundle|'s Info.plist for a given key.
  1178. + (nullable NSString *)configValueFromBundle:(NSBundle *)bundle forKey:(NSString *)key {
  1179. NSString *value;
  1180. id configValue = [bundle objectForInfoDictionaryKey:key];
  1181. if ([configValue isKindOfClass:[NSString class]]) {
  1182. value = configValue;
  1183. }
  1184. return value;
  1185. }
  1186. // Try to generate a |GIDConfiguration| from an |NSBundle|'s Info.plist.
  1187. + (nullable GIDConfiguration *)configurationFromBundle:(NSBundle *)bundle {
  1188. GIDConfiguration *configuration;
  1189. // Retrieve any valid config parameters from the bundle's Info.plist.
  1190. NSString *clientID = [GIDSignIn configValueFromBundle:bundle forKey:kConfigClientIDKey];
  1191. NSString *serverClientID = [GIDSignIn configValueFromBundle:bundle
  1192. forKey:kConfigServerClientIDKey];
  1193. NSString *hostedDomain = [GIDSignIn configValueFromBundle:bundle forKey:kConfigHostedDomainKey];
  1194. NSString *openIDRealm = [GIDSignIn configValueFromBundle:bundle forKey:kConfigOpenIDRealmKey];
  1195. // If we have at least a client ID, try to construct a configuration.
  1196. if (clientID) {
  1197. configuration = [[GIDConfiguration alloc] initWithClientID:clientID
  1198. serverClientID:serverClientID
  1199. hostedDomain:hostedDomain
  1200. openIDRealm:openIDRealm];
  1201. }
  1202. return configuration;
  1203. }
  1204. @end
  1205. NS_ASSUME_NONNULL_END