No Description

FIRSecureTokenService.m 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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 "FIRSecureTokenService.h"
  17. #import "FIRAuth.h"
  18. #import "FIRAuthSerialTaskQueue.h"
  19. #import "FIRAuthBackend.h"
  20. #import "FIRAuthRequestConfiguration.h"
  21. #import "FIRSecureTokenRequest.h"
  22. #import "FIRSecureTokenResponse.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 _authorizationCode
  53. @brief An authorization code which needs to be exchanged for Secure Token Service tokens.
  54. */
  55. NSString *_Nullable _authorizationCode;
  56. /** @var _accessToken
  57. @brief The currently cached access token. Or |nil| if no token is currently cached.
  58. */
  59. NSString *_Nullable _accessToken;
  60. }
  61. - (instancetype)init {
  62. self = [super init];
  63. if (self) {
  64. _taskQueue = [[FIRAuthSerialTaskQueue alloc] init];
  65. }
  66. return self;
  67. }
  68. - (instancetype)initWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration
  69. authorizationCode:(NSString *)authorizationCode {
  70. self = [self init];
  71. if (self) {
  72. _requestConfiguration = requestConfiguration;
  73. _authorizationCode = [authorizationCode copy];
  74. }
  75. return self;
  76. }
  77. - (instancetype)initWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration
  78. accessToken:(nullable NSString *)accessToken
  79. accessTokenExpirationDate:(nullable NSDate *)accessTokenExpirationDate
  80. refreshToken:(NSString *)refreshToken {
  81. self = [self init];
  82. if (self) {
  83. _requestConfiguration = requestConfiguration;
  84. _accessToken = [accessToken copy];
  85. _accessTokenExpirationDate = [accessTokenExpirationDate copy];
  86. _refreshToken = [refreshToken copy];
  87. }
  88. return self;
  89. }
  90. - (void)fetchAccessTokenForcingRefresh:(BOOL)forceRefresh
  91. callback:(FIRFetchAccessTokenCallback)callback {
  92. [_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock complete) {
  93. if (!forceRefresh && [self hasValidAccessToken]) {
  94. complete();
  95. callback(self->_accessToken, nil, NO);
  96. } else {
  97. [self requestAccessToken:^(NSString *_Nullable token,
  98. NSError *_Nullable error,
  99. BOOL tokenUpdated) {
  100. complete();
  101. callback(token, error, tokenUpdated);
  102. }];
  103. }
  104. }];
  105. }
  106. - (NSString *)rawAccessToken {
  107. return _accessToken;
  108. }
  109. #pragma mark - NSSecureCoding
  110. + (BOOL)supportsSecureCoding {
  111. return YES;
  112. }
  113. - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
  114. NSString *refreshToken = [aDecoder decodeObjectOfClass:[NSString class] forKey:kRefreshTokenKey];
  115. NSString *accessToken = [aDecoder decodeObjectOfClass:[NSString class] forKey:kAccessTokenKey];
  116. NSDate *accessTokenExpirationDate =
  117. [aDecoder decodeObjectOfClass:[NSDate class] forKey:kAccessTokenExpirationDateKey];
  118. if (!refreshToken) {
  119. return nil;
  120. }
  121. self = [self init];
  122. if (self) {
  123. _refreshToken = refreshToken;
  124. _accessToken = accessToken;
  125. _accessTokenExpirationDate = accessTokenExpirationDate;
  126. }
  127. return self;
  128. }
  129. - (void)encodeWithCoder:(NSCoder *)aCoder {
  130. // The API key is encoded even it is not used in decoding to be compatible with previous versions
  131. // of the library.
  132. [aCoder encodeObject:_requestConfiguration.APIKey forKey:kAPIKeyCodingKey];
  133. // Authorization code is not encoded because it is not long-lived.
  134. [aCoder encodeObject:_refreshToken forKey:kRefreshTokenKey];
  135. [aCoder encodeObject:_accessToken forKey:kAccessTokenKey];
  136. [aCoder encodeObject:_accessTokenExpirationDate forKey:kAccessTokenExpirationDateKey];
  137. }
  138. #pragma mark - Private methods
  139. /** @fn requestAccessToken:
  140. @brief Makes a request to STS for an access token.
  141. @details This handles both the case that the token has not been granted yet and that it just
  142. needs to be refreshed. The caller is responsible for making sure that this is occurring in
  143. a @c _taskQueue task.
  144. @param callback Called when the fetch is complete. Invoked asynchronously on the main thread in
  145. the future.
  146. @remarks Because this method is guaranteed to only be called from tasks enqueued in
  147. @c _taskQueue, we do not need any @synchronized guards around access to _accessToken/etc.
  148. since only one of those tasks is ever running at a time, and those tasks are the only
  149. access to and mutation of these instance variables.
  150. */
  151. - (void)requestAccessToken:(FIRFetchAccessTokenCallback)callback {
  152. FIRSecureTokenRequest *request;
  153. if (_refreshToken.length) {
  154. request = [FIRSecureTokenRequest refreshRequestWithRefreshToken:_refreshToken
  155. requestConfiguration:_requestConfiguration];
  156. } else {
  157. request = [FIRSecureTokenRequest authCodeRequestWithCode:_authorizationCode
  158. requestConfiguration:_requestConfiguration];
  159. }
  160. [FIRAuthBackend secureToken:request
  161. callback:^(FIRSecureTokenResponse *_Nullable response,
  162. NSError *_Nullable error) {
  163. BOOL tokenUpdated = NO;
  164. NSString *newAccessToken = response.accessToken;
  165. if (newAccessToken.length && ![newAccessToken isEqualToString:self->_accessToken]) {
  166. self->_accessToken = [newAccessToken copy];
  167. self->_accessTokenExpirationDate = response.approximateExpirationDate;
  168. tokenUpdated = YES;
  169. }
  170. NSString *newRefreshToken = response.refreshToken;
  171. if (newRefreshToken.length &&
  172. ![newRefreshToken isEqualToString:self->_refreshToken]) {
  173. self->_refreshToken = [newRefreshToken copy];
  174. tokenUpdated = YES;
  175. }
  176. callback(newAccessToken, error, tokenUpdated);
  177. }];
  178. }
  179. - (BOOL)hasValidAccessToken {
  180. return _accessToken && [_accessTokenExpirationDate timeIntervalSinceNow] > kFiveMinutes;
  181. }
  182. @end
  183. NS_ASSUME_NONNULL_END