FIRSecureTokenService.m 10 KB

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