GIDGoogleUser.m 14 KB

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