FIRSecureTokenService.m 7.3 KB

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