GIDGoogleUser.m 13 KB

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