GIDGoogleUser.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. // Copyright 2022 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/GIDGoogleUser.h"
  15. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  16. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDConfiguration.h"
  17. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDSignIn.h"
  18. #import "GoogleSignIn/Sources/GIDAuthentication.h"
  19. #import "GoogleSignIn/Sources/GIDEMMSupport.h"
  20. #import "GoogleSignIn/Sources/GIDProfileData_Private.h"
  21. #import "GoogleSignIn/Sources/GIDSignIn_Private.h"
  22. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  23. #import "GoogleSignIn/Sources/GIDToken_Private.h"
  24. @import GTMAppAuth;
  25. #ifdef SWIFT_PACKAGE
  26. @import AppAuth;
  27. #else
  28. #import <AppAuth/AppAuth.h>
  29. #endif
  30. NS_ASSUME_NONNULL_BEGIN
  31. // The ID Token claim key for the hosted domain value.
  32. static NSString *const kHostedDomainIDTokenClaimKey = @"hd";
  33. // Key constants used for encode and decode.
  34. static NSString *const kProfileDataKey = @"profileData";
  35. static NSString *const kAuthStateKey = @"authState";
  36. // Parameters for the token exchange endpoint.
  37. static NSString *const kAudienceParameter = @"audience";
  38. static NSString *const kOpenIDRealmParameter = @"openid.realm";
  39. // Additional parameter names for EMM.
  40. static NSString *const kEMMSupportParameterName = @"emm_support";
  41. // Minimal time interval before expiration for the access token or it needs to be refreshed.
  42. static NSTimeInterval const kMinimalTimeToExpire = 60.0;
  43. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  44. @interface GIDGoogleUser ()
  45. @property (nonatomic, strong) id<GTMAuthSessionDelegate> authSessionDelegate;
  46. @end
  47. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  48. @implementation GIDGoogleUser {
  49. GIDConfiguration *_cachedConfiguration;
  50. // A queue for pending token refresh handlers so we don't fire multiple requests in parallel.
  51. // Access to this ivar should be synchronized.
  52. NSMutableArray<GIDGoogleUserCompletion> *_tokenRefreshHandlerQueue;
  53. }
  54. - (nullable NSString *)userID {
  55. NSString *idTokenString = self.idToken.tokenString;
  56. if (idTokenString) {
  57. OIDIDToken *idTokenDecoded = [[OIDIDToken alloc] initWithIDTokenString:idTokenString];
  58. if (idTokenDecoded && idTokenDecoded.subject) {
  59. return [idTokenDecoded.subject copy];
  60. }
  61. }
  62. return nil;
  63. }
  64. - (nullable NSArray<NSString *> *)grantedScopes {
  65. NSArray<NSString *> *grantedScopes;
  66. NSString *grantedScopeString = self.authState.lastTokenResponse.scope;
  67. if (grantedScopeString) {
  68. // If we have a 'scope' parameter from the backend, this is authoritative.
  69. // Remove leading and trailing whitespace.
  70. grantedScopeString = [grantedScopeString stringByTrimmingCharactersInSet:
  71. [NSCharacterSet whitespaceCharacterSet]];
  72. // Tokenize with space as a delimiter.
  73. NSMutableArray<NSString *> *parsedScopes =
  74. [[grantedScopeString componentsSeparatedByString:@" "] mutableCopy];
  75. // Remove empty strings.
  76. [parsedScopes removeObject:@""];
  77. grantedScopes = [parsedScopes copy];
  78. }
  79. return grantedScopes;
  80. }
  81. - (GIDConfiguration *)configuration {
  82. @synchronized(self) {
  83. // Caches the configuration since it would not change for one GIDGoogleUser instance.
  84. if (!_cachedConfiguration) {
  85. NSString *clientID = self.authState.lastAuthorizationResponse.request.clientID;
  86. NSString *serverClientID =
  87. self.authState.lastTokenResponse.request.additionalParameters[kAudienceParameter];
  88. NSString *openIDRealm =
  89. self.authState.lastTokenResponse.request.additionalParameters[kOpenIDRealmParameter];
  90. _cachedConfiguration = [[GIDConfiguration alloc] initWithClientID:clientID
  91. serverClientID:serverClientID
  92. hostedDomain:[self hostedDomain]
  93. openIDRealm:openIDRealm];
  94. };
  95. }
  96. return _cachedConfiguration;
  97. }
  98. - (void)refreshTokensIfNeededWithCompletion:(GIDGoogleUserCompletion)completion {
  99. if (!([self.accessToken.expirationDate timeIntervalSinceNow] < kMinimalTimeToExpire ||
  100. (self.idToken && [self.idToken.expirationDate timeIntervalSinceNow] < kMinimalTimeToExpire))) {
  101. dispatch_async(dispatch_get_main_queue(), ^{
  102. completion(self, nil);
  103. });
  104. return;
  105. }
  106. @synchronized (_tokenRefreshHandlerQueue) {
  107. // Push the handler into the callback queue.
  108. [_tokenRefreshHandlerQueue addObject:[completion copy]];
  109. if (_tokenRefreshHandlerQueue.count > 1) {
  110. // This is not the first handler in the queue, no fetch is needed.
  111. return;
  112. }
  113. }
  114. // This is the first handler in the queue, a fetch is needed.
  115. NSMutableDictionary *additionalParameters = [@{} mutableCopy];
  116. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  117. [additionalParameters addEntriesFromDictionary:
  118. [GIDEMMSupport updatedEMMParametersWithParameters:
  119. self.authState.lastTokenResponse.request.additionalParameters]];
  120. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  121. [additionalParameters addEntriesFromDictionary:
  122. self.authState.lastTokenResponse.request.additionalParameters];
  123. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  124. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  125. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  126. OIDTokenRequest *tokenRefreshRequest =
  127. [self.authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  128. [OIDAuthorizationService performTokenRequest:tokenRefreshRequest
  129. originalAuthorizationResponse:self.authState.lastAuthorizationResponse
  130. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  131. NSError *_Nullable error) {
  132. if (tokenResponse) {
  133. [self.authState updateWithTokenResponse:tokenResponse error:nil];
  134. } else {
  135. if (error.domain == OIDOAuthTokenErrorDomain) {
  136. [self.authState updateWithAuthorizationError:error];
  137. }
  138. }
  139. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  140. [GIDEMMSupport handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  141. // Process the handler queue to call back.
  142. NSArray<GIDGoogleUserCompletion> *refreshTokensHandlerQueue;
  143. @synchronized(self->_tokenRefreshHandlerQueue) {
  144. refreshTokensHandlerQueue = [self->_tokenRefreshHandlerQueue copy];
  145. [self->_tokenRefreshHandlerQueue removeAllObjects];
  146. }
  147. for (GIDGoogleUserCompletion completion in refreshTokensHandlerQueue) {
  148. dispatch_async(dispatch_get_main_queue(), ^{
  149. completion(error ? nil : self, error);
  150. });
  151. }
  152. }];
  153. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  154. NSArray<GIDGoogleUserCompletion> *refreshTokensHandlerQueue;
  155. @synchronized(self->_tokenRefreshHandlerQueue) {
  156. refreshTokensHandlerQueue = [self->_tokenRefreshHandlerQueue copy];
  157. [self->_tokenRefreshHandlerQueue removeAllObjects];
  158. }
  159. for (GIDGoogleUserCompletion completion in refreshTokensHandlerQueue) {
  160. dispatch_async(dispatch_get_main_queue(), ^{
  161. completion(error ? nil : self, error);
  162. });
  163. }
  164. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  165. }];
  166. }
  167. - (OIDAuthState *)authState {
  168. return ((GTMAuthSession *)self.fetcherAuthorizer).authState;
  169. }
  170. - (void)addScopes:(NSArray<NSString *> *)scopes
  171. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  172. presentingViewController:(UIViewController *)presentingViewController
  173. #elif TARGET_OS_OSX
  174. presentingWindow:(NSWindow *)presentingWindow
  175. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  176. completion:(nullable void (^)(GIDSignInResult *_Nullable signInResult,
  177. NSError *_Nullable error))completion {
  178. if (self != GIDSignIn.sharedInstance.currentUser) {
  179. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  180. code:kGIDSignInErrorCodeMismatchWithCurrentUser
  181. userInfo:nil];
  182. if (completion) {
  183. dispatch_async(dispatch_get_main_queue(), ^{
  184. completion(nil, error);
  185. });
  186. }
  187. return;
  188. }
  189. [GIDSignIn.sharedInstance addScopes:scopes
  190. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  191. presentingViewController:presentingViewController
  192. #elif TARGET_OS_OSX
  193. presentingWindow:presentingWindow
  194. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  195. completion:completion];
  196. }
  197. #pragma mark - Private Methods
  198. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  199. - (nullable NSString *)emmSupport {
  200. return self.authState.lastAuthorizationResponse
  201. .request.additionalParameters[kEMMSupportParameterName];
  202. }
  203. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  204. - (instancetype)initWithAuthState:(OIDAuthState *)authState
  205. profileData:(nullable GIDProfileData *)profileData {
  206. self = [super init];
  207. if (self) {
  208. _tokenRefreshHandlerQueue = [[NSMutableArray alloc] init];
  209. _profile = profileData;
  210. GTMAuthSession *authSession = [[GTMAuthSession alloc] initWithAuthState:authState];
  211. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  212. _authSessionDelegate = [[GIDEMMSupport alloc] init];
  213. authSession.delegate = _authSessionDelegate;
  214. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  215. authSession.authState.stateChangeDelegate = self;
  216. _fetcherAuthorizer = authSession;
  217. [self updateTokensWithAuthState:authState];
  218. }
  219. return self;
  220. }
  221. - (void)updateWithTokenResponse:(OIDTokenResponse *)tokenResponse
  222. authorizationResponse:(OIDAuthorizationResponse *)authorizationResponse
  223. profileData:(nullable GIDProfileData *)profileData {
  224. @synchronized(self) {
  225. _profile = profileData;
  226. // We don't want to trigger the delegate before we update authState completely. So we unset the
  227. // delegate before the first update. Also the order of updates is important because
  228. // `updateWithAuthorizationResponse` would clear the last token reponse and refresh token.
  229. // TODO: Rewrite authState update logic when the issue is addressed.(openid/AppAuth-iOS#728)
  230. self.authState.stateChangeDelegate = nil;
  231. [self.authState updateWithAuthorizationResponse:authorizationResponse error:nil];
  232. self.authState.stateChangeDelegate = self;
  233. [self.authState updateWithTokenResponse:tokenResponse error:nil];
  234. }
  235. }
  236. - (void)updateTokensWithAuthState:(OIDAuthState *)authState {
  237. GIDToken *accessToken =
  238. [[GIDToken alloc] initWithTokenString:authState.lastTokenResponse.accessToken
  239. expirationDate:authState.lastTokenResponse.accessTokenExpirationDate];
  240. if (![self.accessToken isEqualToToken:accessToken]) {
  241. self.accessToken = accessToken;
  242. }
  243. GIDToken *refreshToken = [[GIDToken alloc] initWithTokenString:authState.refreshToken
  244. expirationDate:nil];
  245. if (![self.refreshToken isEqualToToken:refreshToken]) {
  246. self.refreshToken = refreshToken;
  247. }
  248. GIDToken *idToken;
  249. NSString *idTokenString = authState.lastTokenResponse.idToken;
  250. if (idTokenString) {
  251. NSDate *idTokenExpirationDate =
  252. [[[OIDIDToken alloc] initWithIDTokenString:idTokenString] expiresAt];
  253. idToken = [[GIDToken alloc] initWithTokenString:idTokenString
  254. expirationDate:idTokenExpirationDate];
  255. } else {
  256. idToken = nil;
  257. }
  258. if ((self.idToken || idToken) && ![self.idToken isEqualToToken:idToken]) {
  259. self.idToken = idToken;
  260. }
  261. }
  262. #pragma mark - Helpers
  263. - (nullable NSString *)hostedDomain {
  264. NSString *idTokenString = self.idToken.tokenString;
  265. if (idTokenString) {
  266. OIDIDToken *idTokenDecoded = [[OIDIDToken alloc] initWithIDTokenString:idTokenString];
  267. if (idTokenDecoded && idTokenDecoded.claims[kHostedDomainIDTokenClaimKey]) {
  268. return idTokenDecoded.claims[kHostedDomainIDTokenClaimKey];
  269. }
  270. }
  271. return nil;
  272. }
  273. #pragma mark - OIDAuthStateChangeDelegate
  274. - (void)didChangeState:(OIDAuthState *)state {
  275. [self updateTokensWithAuthState:state];
  276. }
  277. #pragma mark - NSSecureCoding
  278. + (BOOL)supportsSecureCoding {
  279. return YES;
  280. }
  281. - (nullable instancetype)initWithCoder:(NSCoder *)decoder {
  282. self = [super init];
  283. if (self) {
  284. GIDProfileData *profile =
  285. [decoder decodeObjectOfClass:[GIDProfileData class] forKey:kProfileDataKey];
  286. OIDAuthState *authState;
  287. if ([decoder containsValueForKey:kAuthStateKey]) { // Current encoding
  288. authState = [decoder decodeObjectOfClass:[OIDAuthState class] forKey:kAuthStateKey];
  289. } else { // Old encoding
  290. GIDAuthentication *authentication = [decoder decodeObjectOfClass:[GIDAuthentication class]
  291. forKey:@"authentication"];
  292. authState = authentication.authState;
  293. }
  294. self = [self initWithAuthState:authState profileData:profile];
  295. }
  296. return self;
  297. }
  298. - (void)encodeWithCoder:(NSCoder *)encoder {
  299. [encoder encodeObject:_profile forKey:kProfileDataKey];
  300. [encoder encodeObject:self.authState forKey:kAuthStateKey];
  301. }
  302. @end
  303. NS_ASSUME_NONNULL_END