Нема описа

FIRSecureTokenService.m 7.4KB

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