GIDGoogleUser.m 14 KB

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