FIRSecureTokenService.m 7.8 KB

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