GIDGoogleUser.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. 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)refreshTokensIfNeededWithCompletion:(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. - (void)addScopes:(NSArray<NSString *> *)scopes
  164. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  165. presentingViewController:(UIViewController *)presentingViewController
  166. #elif TARGET_OS_OSX
  167. presentingWindow:(NSWindow *)presentingWindow
  168. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  169. completion:(nullable void (^)(GIDSignInResult *_Nullable signInResult,
  170. NSError *_Nullable error))completion {
  171. if (self != GIDSignIn.sharedInstance.currentUser) {
  172. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  173. code:kGIDSignInErrorCodeMismatchWithCurrentUser
  174. userInfo:nil];
  175. if (completion) {
  176. dispatch_async(dispatch_get_main_queue(), ^{
  177. completion(nil, error);
  178. });
  179. }
  180. return;
  181. }
  182. [GIDSignIn.sharedInstance addScopes:scopes
  183. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  184. presentingViewController:presentingViewController
  185. #elif TARGET_OS_OSX
  186. presentingWindow:presentingWindow
  187. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  188. completion:completion];
  189. }
  190. #pragma mark - Private Methods
  191. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  192. - (nullable NSString *)emmSupport {
  193. return self.authState.lastAuthorizationResponse
  194. .request.additionalParameters[kEMMSupportParameterName];
  195. }
  196. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  197. - (instancetype)initWithAuthState:(OIDAuthState *)authState
  198. profileData:(nullable GIDProfileData *)profileData {
  199. self = [super init];
  200. if (self) {
  201. _tokenRefreshHandlerQueue = [[NSMutableArray alloc] init];
  202. _profile = profileData;
  203. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  204. GTMAppAuthFetcherAuthorization *authorization = self.emmSupport ?
  205. [[GIDAppAuthFetcherAuthorizationWithEMMSupport alloc] initWithAuthState:authState] :
  206. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  207. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  208. GTMAppAuthFetcherAuthorization *authorization =
  209. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  210. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  211. authorization.tokenRefreshDelegate = self;
  212. authorization.authState.stateChangeDelegate = self;
  213. self.fetcherAuthorizer = authorization;
  214. [self updateTokensWithAuthState:authState];
  215. }
  216. return self;
  217. }
  218. - (void)updateWithTokenResponse:(OIDTokenResponse *)tokenResponse
  219. authorizationResponse:(OIDAuthorizationResponse *)authorizationResponse
  220. profileData:(nullable GIDProfileData *)profileData {
  221. @synchronized(self) {
  222. _profile = profileData;
  223. // We don't want to trigger the delegate before we update authState completely. So we unset the
  224. // delegate before the first update. Also the order of updates is important because
  225. // `updateWithAuthorizationResponse` would clear the last token reponse and refresh token.
  226. // TODO: Rewrite authState update logic when the issue is addressed.(openid/AppAuth-iOS#728)
  227. self.authState.stateChangeDelegate = nil;
  228. [self.authState updateWithAuthorizationResponse:authorizationResponse error:nil];
  229. self.authState.stateChangeDelegate = self;
  230. [self.authState updateWithTokenResponse:tokenResponse error:nil];
  231. }
  232. }
  233. - (void)updateTokensWithAuthState:(OIDAuthState *)authState {
  234. GIDToken *accessToken =
  235. [[GIDToken alloc] initWithTokenString:authState.lastTokenResponse.accessToken
  236. expirationDate:authState.lastTokenResponse.accessTokenExpirationDate];
  237. if (![self.accessToken isEqualToToken:accessToken]) {
  238. self.accessToken = accessToken;
  239. }
  240. GIDToken *refreshToken = [[GIDToken alloc] initWithTokenString:authState.refreshToken
  241. expirationDate:nil];
  242. if (![self.refreshToken isEqualToToken:refreshToken]) {
  243. self.refreshToken = refreshToken;
  244. }
  245. GIDToken *idToken;
  246. NSString *idTokenString = authState.lastTokenResponse.idToken;
  247. if (idTokenString) {
  248. NSDate *idTokenExpirationDate =
  249. [[[OIDIDToken alloc] initWithIDTokenString:idTokenString] expiresAt];
  250. idToken = [[GIDToken alloc] initWithTokenString:idTokenString
  251. expirationDate:idTokenExpirationDate];
  252. } else {
  253. idToken = nil;
  254. }
  255. if ((self.idToken || idToken) && ![self.idToken isEqualToToken:idToken]) {
  256. self.idToken = idToken;
  257. }
  258. }
  259. #pragma mark - Helpers
  260. - (nullable NSString *)hostedDomain {
  261. NSString *idTokenString = self.idToken.tokenString;
  262. if (idTokenString) {
  263. OIDIDToken *idTokenDecoded = [[OIDIDToken alloc] initWithIDTokenString:idTokenString];
  264. if (idTokenDecoded && idTokenDecoded.claims[kHostedDomainIDTokenClaimKey]) {
  265. return idTokenDecoded.claims[kHostedDomainIDTokenClaimKey];
  266. }
  267. }
  268. return nil;
  269. }
  270. #pragma mark - GTMAppAuthFetcherAuthorizationTokenRefreshDelegate
  271. - (nullable NSDictionary *)additionalRefreshParameters:
  272. (GTMAppAuthFetcherAuthorization *)authorization {
  273. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  274. return [GIDEMMSupport updatedEMMParametersWithParameters:
  275. authorization.authState.lastTokenResponse.request.additionalParameters];
  276. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  277. return authorization.authState.lastTokenResponse.request.additionalParameters;
  278. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  279. }
  280. #pragma mark - OIDAuthStateChangeDelegate
  281. - (void)didChangeState:(OIDAuthState *)state {
  282. [self updateTokensWithAuthState:state];
  283. }
  284. #pragma mark - NSSecureCoding
  285. + (BOOL)supportsSecureCoding {
  286. return YES;
  287. }
  288. - (nullable instancetype)initWithCoder:(NSCoder *)decoder {
  289. self = [super init];
  290. if (self) {
  291. GIDProfileData *profile =
  292. [decoder decodeObjectOfClass:[GIDProfileData class] forKey:kProfileDataKey];
  293. OIDAuthState *authState;
  294. if ([decoder containsValueForKey:kAuthStateKey]) { // Current encoding
  295. authState = [decoder decodeObjectOfClass:[OIDAuthState class] forKey:kAuthStateKey];
  296. } else { // Old encoding
  297. GIDAuthentication *authentication = [decoder decodeObjectOfClass:[GIDAuthentication class]
  298. forKey:@"authentication"];
  299. authState = authentication.authState;
  300. }
  301. self = [self initWithAuthState:authState profileData:profile];
  302. }
  303. return self;
  304. }
  305. - (void)encodeWithCoder:(NSCoder *)encoder {
  306. [encoder encodeObject:_profile forKey:kProfileDataKey];
  307. [encoder encodeObject:self.authState forKey:kAuthStateKey];
  308. }
  309. @end
  310. NS_ASSUME_NONNULL_END