FIRSecureTokenService.m 8.9 KB

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