FIRSecureTokenService.m 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseAuth/Sources/SystemService/FIRSecureTokenService.h"
  17. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRAuth.h"
  18. #import "FirebaseAuth/Sources/Auth/FIRAuthSerialTaskQueue.h"
  19. #import "FirebaseAuth/Sources/Auth/FIRAuth_Internal.h"
  20. #import "FirebaseAuth/Sources/Backend/FIRAuthBackend.h"
  21. #import "FirebaseAuth-Swift.h"
  22. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  23. NS_ASSUME_NONNULL_BEGIN
  24. /** @var kAPIKeyCodingKey
  25. @brief The key used to encode the APIKey for NSSecureCoding.
  26. */
  27. static NSString *const kAPIKeyCodingKey = @"APIKey";
  28. /** @var kRefreshTokenKey
  29. @brief The key used to encode the refresh token for NSSecureCoding.
  30. */
  31. static NSString *const kRefreshTokenKey = @"refreshToken";
  32. /** @var kAccessTokenKey
  33. @brief The key used to encode the access token for NSSecureCoding.
  34. */
  35. static NSString *const kAccessTokenKey = @"accessToken";
  36. /** @var kAccessTokenExpirationDateKey
  37. @brief The key used to encode the access token expiration date for NSSecureCoding.
  38. */
  39. static NSString *const kAccessTokenExpirationDateKey = @"accessTokenExpirationDate";
  40. /** @var kFiveMinutes
  41. @brief Five minutes (in seconds.)
  42. */
  43. static const NSTimeInterval kFiveMinutes = 5 * 60;
  44. @interface FIRSecureTokenService ()
  45. - (instancetype)init NS_DESIGNATED_INITIALIZER;
  46. @end
  47. @implementation FIRSecureTokenService {
  48. /** @var _taskQueue
  49. @brief Used to serialize all requests for access tokens.
  50. */
  51. FIRAuthSerialTaskQueue *_taskQueue;
  52. /** @var _accessToken
  53. @brief The currently cached access token. Or |nil| if no token is currently cached.
  54. */
  55. NSString *_Nullable _accessToken;
  56. }
  57. - (instancetype)init {
  58. self = [super init];
  59. if (self) {
  60. _taskQueue = [[FIRAuthSerialTaskQueue alloc] init];
  61. }
  62. return self;
  63. }
  64. - (instancetype)initWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration
  65. accessToken:(nullable NSString *)accessToken
  66. accessTokenExpirationDate:(nullable NSDate *)accessTokenExpirationDate
  67. refreshToken:(NSString *)refreshToken {
  68. self = [self init];
  69. if (self) {
  70. _requestConfiguration = requestConfiguration;
  71. _accessToken = [accessToken copy];
  72. _accessTokenExpirationDate = [accessTokenExpirationDate copy];
  73. _refreshToken = [refreshToken copy];
  74. }
  75. return self;
  76. }
  77. - (void)fetchAccessTokenForcingRefresh:(BOOL)forceRefresh
  78. callback:(FIRFetchAccessTokenCallback)callback {
  79. [_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock complete) {
  80. if (!forceRefresh && [self hasValidAccessToken]) {
  81. complete();
  82. callback(self->_accessToken, nil, NO);
  83. } else {
  84. FIRLogDebug(kFIRLoggerAuth, @"I-AUT000017", @"Fetching new token from backend.");
  85. [self requestAccessToken:YES
  86. callback:^(NSString *_Nullable token, NSError *_Nullable error,
  87. BOOL tokenUpdated) {
  88. complete();
  89. callback(token, error, tokenUpdated);
  90. }];
  91. }
  92. }];
  93. }
  94. - (NSString *)rawAccessToken {
  95. return _accessToken;
  96. }
  97. #pragma mark - NSSecureCoding
  98. + (BOOL)supportsSecureCoding {
  99. return YES;
  100. }
  101. - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
  102. NSString *refreshToken = [aDecoder decodeObjectOfClass:[NSString class] forKey:kRefreshTokenKey];
  103. NSString *accessToken = [aDecoder decodeObjectOfClass:[NSString class] forKey:kAccessTokenKey];
  104. NSDate *accessTokenExpirationDate = [aDecoder decodeObjectOfClass:[NSDate class]
  105. forKey:kAccessTokenExpirationDateKey];
  106. if (!refreshToken) {
  107. return nil;
  108. }
  109. self = [self init];
  110. if (self) {
  111. _refreshToken = refreshToken;
  112. _accessToken = accessToken;
  113. _accessTokenExpirationDate = accessTokenExpirationDate;
  114. }
  115. return self;
  116. }
  117. - (void)encodeWithCoder:(NSCoder *)aCoder {
  118. // The API key is encoded even it is not used in decoding to be compatible with previous versions
  119. // of the library.
  120. [aCoder encodeObject:_requestConfiguration.APIKey forKey:kAPIKeyCodingKey];
  121. // Authorization code is not encoded because it is not long-lived.
  122. [aCoder encodeObject:_refreshToken forKey:kRefreshTokenKey];
  123. [aCoder encodeObject:_accessToken forKey:kAccessTokenKey];
  124. [aCoder encodeObject:_accessTokenExpirationDate forKey:kAccessTokenExpirationDateKey];
  125. }
  126. #pragma mark - Private methods
  127. /** @fn requestAccessToken:
  128. @brief Makes a request to STS for an access token.
  129. @details This handles both the case that the token has not been granted yet and that it just
  130. needs to be refreshed. The caller is responsible for making sure that this is occurring in
  131. a @c _taskQueue task.
  132. @param callback Called when the fetch is complete. Invoked asynchronously on the main thread in
  133. the future.
  134. @remarks Because this method is guaranteed to only be called from tasks enqueued in
  135. @c _taskQueue, we do not need any @synchronized guards around access to _accessToken/etc.
  136. since only one of those tasks is ever running at a time, and those tasks are the only
  137. access to and mutation of these instance variables.
  138. */
  139. - (void)requestAccessToken:(BOOL)retryIfExpired callback:(FIRFetchAccessTokenCallback)callback {
  140. FIRSecureTokenRequest *request =
  141. [FIRSecureTokenRequest refreshRequestWithRefreshToken:_refreshToken
  142. requestConfiguration:_requestConfiguration];
  143. [FIRAuthBackend
  144. secureToken:request
  145. callback:^(FIRSecureTokenResponse *_Nullable response, NSError *_Nullable error) {
  146. BOOL tokenUpdated = NO;
  147. NSString *newAccessToken = response.accessToken;
  148. if (newAccessToken.length && ![newAccessToken isEqualToString:self->_accessToken]) {
  149. FIRAuthTokenResult *tokenResult =
  150. [FIRAuthTokenResult tokenResultWithToken:newAccessToken];
  151. // There is an edge case where the request for a new access token may be made right
  152. // before the app goes inactive, resulting in the callback being invoked much later
  153. // with an expired access token. This does not fully solve the issue, as if the
  154. // callback is invoked less than an hour after the request is made, a token is not
  155. // re-requested here but the approximateExpirationDate will still be off since that is
  156. // computed at the time the token is received.
  157. if (retryIfExpired &&
  158. [tokenResult.expirationDate timeIntervalSinceNow] <= kFiveMinutes) {
  159. // We only retry once, to avoid an infinite loop in the case that an end-user has
  160. // their local time skewed by over an hour.
  161. [self requestAccessToken:NO callback:callback];
  162. return;
  163. }
  164. self->_accessToken = [newAccessToken copy];
  165. self->_accessTokenExpirationDate = response.approximateExpirationDate;
  166. tokenUpdated = YES;
  167. FIRLogDebug(kFIRLoggerAuth, @"I-AUT000017",
  168. @"Updated access token. Estimated expiration date: %@, current date: %@",
  169. self->_accessTokenExpirationDate, [NSDate date]);
  170. }
  171. NSString *newRefreshToken = response.refreshToken;
  172. if (newRefreshToken.length && ![newRefreshToken isEqualToString:self->_refreshToken]) {
  173. self->_refreshToken = [newRefreshToken copy];
  174. tokenUpdated = YES;
  175. }
  176. callback(newAccessToken, error, tokenUpdated);
  177. }];
  178. }
  179. - (BOOL)hasValidAccessToken {
  180. BOOL hasValidAccessToken =
  181. _accessToken && [_accessTokenExpirationDate timeIntervalSinceNow] > kFiveMinutes;
  182. if (hasValidAccessToken) {
  183. FIRLogDebug(kFIRLoggerAuth, @"I-AUT000017",
  184. @"Has valid access token. Estimated expiration date: %@, current date: %@",
  185. _accessTokenExpirationDate, [NSDate date]);
  186. } else {
  187. FIRLogDebug(
  188. kFIRLoggerAuth, @"I-AUT000017",
  189. @"Does not have valid access token. Estimated expiration date: %@, current date: %@",
  190. _accessTokenExpirationDate, [NSDate date]);
  191. }
  192. return hasValidAccessToken;
  193. }
  194. @end
  195. NS_ASSUME_NONNULL_END