GIDAuthentication.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDAuthentication.h"
  15. #import "GoogleSignIn/Sources/GIDAuthentication_Private.h"
  16. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  17. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  18. #import "GoogleSignIn/Sources/GIDMDMPasscodeState.h"
  19. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDSignIn.h"
  20. #ifdef SWIFT_PACKAGE
  21. @import AppAuth;
  22. @import GTMAppAuth;
  23. #else
  24. #import <AppAuth/OIDAuthState.h>
  25. #import <AppAuth/OIDAuthorizationRequest.h>
  26. #import <AppAuth/OIDAuthorizationResponse.h>
  27. #import <AppAuth/OIDAuthorizationService.h>
  28. #import <AppAuth/OIDError.h>
  29. #import <AppAuth/OIDIDToken.h>
  30. #import <AppAuth/OIDTokenRequest.h>
  31. #import <AppAuth/OIDTokenResponse.h>
  32. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization.h>
  33. #endif
  34. NS_ASSUME_NONNULL_BEGIN
  35. // Minimal time interval before expiration for the access token or it needs to be refreshed.
  36. NSTimeInterval kMinimalTimeToExpire = 60.0;
  37. // Key constants used for encode and decode.
  38. static NSString *const kAuthStateKey = @"authState";
  39. // Additional parameter names for EMM.
  40. static NSString *const kEMMSupportParameterName = @"emm_support";
  41. static NSString *const kEMMOSVersionParameterName = @"device_os";
  42. static NSString *const kEMMPasscodeInfoParameterName = @"emm_passcode_info";
  43. // Old UIDevice system name for iOS.
  44. static NSString *const kOldIOSSystemName = @"iPhone OS";
  45. // New UIDevice system name for iOS.
  46. static NSString *const kNewIOSSystemName = @"iOS";
  47. // The specialized GTMAppAuthFetcherAuthorization delegate that handles potential EMM error
  48. // responses.
  49. @interface GTMAppAuthFetcherAuthorizationEMMChainedDelegate : NSObject
  50. // Initializes with chained delegate and selector.
  51. - (instancetype)initWithDelegate:(id)delegate selector:(SEL)selector;
  52. // The callback method for GTMAppAuthFetcherAuthorization to invoke.
  53. - (void)authentication:(GTMAppAuthFetcherAuthorization *)auth
  54. request:(NSMutableURLRequest *)request
  55. finishedWithError:(nullable NSError *)error;
  56. @end
  57. @implementation GTMAppAuthFetcherAuthorizationEMMChainedDelegate {
  58. // We use a weak reference here to match GTMAppAuthFetcherAuthorization.
  59. __weak id _delegate;
  60. SEL _selector;
  61. // We need to maintain a reference to the chained delegate because GTMAppAuthFetcherAuthorization
  62. // only keeps a weak reference.
  63. GTMAppAuthFetcherAuthorizationEMMChainedDelegate *_retained_self;
  64. }
  65. - (instancetype)initWithDelegate:(id)delegate selector:(SEL)selector {
  66. self = [super init];
  67. if (self) {
  68. _delegate = delegate;
  69. _selector = selector;
  70. _retained_self = self;
  71. }
  72. return self;
  73. }
  74. - (void)authentication:(GTMAppAuthFetcherAuthorization *)auth
  75. request:(NSMutableURLRequest *)request
  76. finishedWithError:(nullable NSError *)error {
  77. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  78. if (!_delegate || !_selector) {
  79. return;
  80. }
  81. NSMethodSignature *signature = [_delegate methodSignatureForSelector:_selector];
  82. if (!signature) {
  83. return;
  84. }
  85. id argument1 = auth;
  86. id argument2 = request;
  87. id argument3 = error;
  88. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
  89. [invocation setTarget:_delegate]; // index 0
  90. [invocation setSelector:_selector]; // index 1
  91. [invocation setArgument:&argument1 atIndex:2];
  92. [invocation setArgument:&argument2 atIndex:3];
  93. [invocation setArgument:&argument3 atIndex:4];
  94. [invocation invoke];
  95. }];
  96. // Prepare to deallocate the chained delegate instance because the above block will retain the
  97. // iVar references it uses.
  98. _retained_self = nil;
  99. }
  100. @end
  101. // A specialized GTMAppAuthFetcherAuthorization subclass with EMM support.
  102. @interface GTMAppAuthFetcherAuthorizationWithEMMSupport : GTMAppAuthFetcherAuthorization
  103. @end
  104. @implementation GTMAppAuthFetcherAuthorizationWithEMMSupport
  105. - (void)authorizeRequest:(nullable NSMutableURLRequest *)request
  106. delegate:(id)delegate
  107. didFinishSelector:(SEL)sel {
  108. GTMAppAuthFetcherAuthorizationEMMChainedDelegate *chainedDelegate =
  109. [[GTMAppAuthFetcherAuthorizationEMMChainedDelegate alloc] initWithDelegate:delegate
  110. selector:sel];
  111. [super authorizeRequest:request
  112. delegate:chainedDelegate
  113. didFinishSelector:@selector(authentication:request:finishedWithError:)];
  114. }
  115. - (void)authorizeRequest:(nullable NSMutableURLRequest *)request
  116. completionHandler:(GTMAppAuthFetcherAuthorizationCompletion)handler {
  117. [super authorizeRequest:request completionHandler:^(NSError *_Nullable error) {
  118. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  119. handler(error);
  120. }];
  121. }];
  122. }
  123. @end
  124. @implementation GIDAuthentication {
  125. // A queue for pending authentication handlers so we don't fire multiple requests in parallel.
  126. // Access to this ivar should be synchronized.
  127. NSMutableArray *_authenticationHandlerQueue;
  128. }
  129. - (instancetype)initWithAuthState:(OIDAuthState *)authState {
  130. if (!authState) {
  131. return nil;
  132. }
  133. self = [super init];
  134. if (self) {
  135. _authenticationHandlerQueue = [[NSMutableArray alloc] init];
  136. _authState = authState;
  137. }
  138. return self;
  139. }
  140. #pragma mark - Public property accessors
  141. - (NSString *)clientID {
  142. return _authState.lastAuthorizationResponse.request.clientID;
  143. }
  144. - (NSString *)accessToken {
  145. return _authState.lastTokenResponse.accessToken;
  146. }
  147. - (NSDate *)accessTokenExpirationDate {
  148. return _authState.lastTokenResponse.accessTokenExpirationDate;
  149. }
  150. - (NSString *)refreshToken {
  151. return _authState.refreshToken;
  152. }
  153. - (nullable NSString *)idToken {
  154. return _authState.lastTokenResponse.idToken;
  155. }
  156. - (nullable NSDate *)idTokenExpirationDate {
  157. return [[[OIDIDToken alloc] initWithIDTokenString:self.idToken] expiresAt];
  158. }
  159. #pragma mark - Private property accessors
  160. - (NSString *)emmSupport {
  161. return
  162. _authState.lastAuthorizationResponse.request.additionalParameters[kEMMSupportParameterName];
  163. }
  164. #pragma mark - Public methods
  165. - (id<GTMFetcherAuthorizationProtocol>)fetcherAuthorizer {
  166. GTMAppAuthFetcherAuthorization *authorization = self.emmSupport ?
  167. [[GTMAppAuthFetcherAuthorizationWithEMMSupport alloc] initWithAuthState:_authState] :
  168. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:_authState];
  169. authorization.tokenRefreshDelegate = self;
  170. return authorization;
  171. }
  172. - (void)doWithFreshTokens:(GIDAuthenticationAction)action {
  173. if (!([self.accessTokenExpirationDate timeIntervalSinceNow] < kMinimalTimeToExpire ||
  174. (self.idToken && [self.idTokenExpirationDate timeIntervalSinceNow] < kMinimalTimeToExpire))) {
  175. action(self, nil);
  176. return;
  177. }
  178. @synchronized (_authenticationHandlerQueue) {
  179. // Push the handler into the callback queue.
  180. [_authenticationHandlerQueue addObject:[action copy]];
  181. if (_authenticationHandlerQueue.count > 1) {
  182. // This is not the first handler in the queue, no fetch is needed.
  183. return;
  184. }
  185. }
  186. // This is the first handler in the queue, a fetch is needed.
  187. OIDTokenRequest *tokenRefreshRequest =
  188. [_authState tokenRefreshRequestWithAdditionalParameters:
  189. [GIDAuthentication updatedEMMParametersWithParameters:
  190. _authState.lastTokenResponse.request.additionalParameters]];
  191. [OIDAuthorizationService performTokenRequest:tokenRefreshRequest
  192. originalAuthorizationResponse:_authState.lastAuthorizationResponse
  193. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  194. NSError *_Nullable error) {
  195. if (tokenResponse) {
  196. [self willChangeValueForKey:NSStringFromSelector(@selector(accessToken))];
  197. [self willChangeValueForKey:NSStringFromSelector(@selector(accessTokenExpirationDate))];
  198. [self willChangeValueForKey:NSStringFromSelector(@selector(idToken))];
  199. [self willChangeValueForKey:NSStringFromSelector(@selector(idTokenExpirationDate))];
  200. [_authState updateWithTokenResponse:tokenResponse error:nil];
  201. [self didChangeValueForKey:NSStringFromSelector(@selector(accessToken))];
  202. [self didChangeValueForKey:NSStringFromSelector(@selector(accessTokenExpirationDate))];
  203. [self didChangeValueForKey:NSStringFromSelector(@selector(idToken))];
  204. [self didChangeValueForKey:NSStringFromSelector(@selector(idTokenExpirationDate))];
  205. } else {
  206. if (error.domain == OIDOAuthTokenErrorDomain) {
  207. [_authState updateWithAuthorizationError:error];
  208. }
  209. }
  210. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  211. // Process the handler queue to call back.
  212. NSArray *authenticationHandlerQueue;
  213. @synchronized(_authenticationHandlerQueue) {
  214. authenticationHandlerQueue = [_authenticationHandlerQueue copy];
  215. [_authenticationHandlerQueue removeAllObjects];
  216. }
  217. for (GIDAuthenticationAction action in authenticationHandlerQueue) {
  218. action(error ? nil : self, error);
  219. }
  220. }];
  221. }];
  222. }
  223. #pragma mark - Private methods
  224. + (NSDictionary *)parametersWithParameters:(NSDictionary *)parameters
  225. emmSupport:(nullable NSString *)emmSupport
  226. isPasscodeInfoRequired:(BOOL)isPasscodeInfoRequired {
  227. if (!emmSupport) {
  228. return parameters;
  229. }
  230. NSMutableDictionary *allParameters = [(parameters ?: @{}) mutableCopy];
  231. allParameters[kEMMSupportParameterName] = emmSupport;
  232. UIDevice *device = [UIDevice currentDevice];
  233. NSString *systemName = device.systemName;
  234. if ([systemName isEqualToString:kOldIOSSystemName]) {
  235. systemName = kNewIOSSystemName;
  236. }
  237. allParameters[kEMMOSVersionParameterName] =
  238. [NSString stringWithFormat:@"%@ %@", systemName, device.systemVersion];
  239. if (isPasscodeInfoRequired) {
  240. allParameters[kEMMPasscodeInfoParameterName] = [GIDMDMPasscodeState passcodeState].info;
  241. }
  242. allParameters[kSDKVersionLoggingParameter] = GIDVersion();
  243. return allParameters;
  244. }
  245. + (NSDictionary *)updatedEMMParametersWithParameters:(NSDictionary *)parameters {
  246. return [self parametersWithParameters:parameters
  247. emmSupport:parameters[kEMMSupportParameterName]
  248. isPasscodeInfoRequired:parameters[kEMMPasscodeInfoParameterName] != nil];
  249. }
  250. + (void)handleTokenFetchEMMError:(nullable NSError *)error
  251. completion:(void (^)(NSError *_Nullable))completion {
  252. NSDictionary *errorJSON = error.userInfo[OIDOAuthErrorResponseErrorKey];
  253. if (errorJSON) {
  254. __block BOOL handled = NO;
  255. handled = [[GIDEMMErrorHandler sharedInstance] handleErrorFromResponse:errorJSON
  256. completion:^() {
  257. if (handled) {
  258. completion([NSError errorWithDomain:kGIDSignInErrorDomain
  259. code:kGIDSignInErrorCodeEMM
  260. userInfo:error.userInfo]);
  261. } else {
  262. completion(error);
  263. }
  264. }];
  265. } else {
  266. completion(error);
  267. }
  268. }
  269. #pragma mark - GTMAppAuthFetcherAuthorizationTokenRefreshDelegate
  270. - (nullable NSDictionary *)additionalRefreshParameters:
  271. (GTMAppAuthFetcherAuthorization *)authorization {
  272. return [GIDAuthentication updatedEMMParametersWithParameters:
  273. authorization.authState.lastTokenResponse.request.additionalParameters];
  274. }
  275. #pragma mark - NSSecureCoding
  276. + (BOOL)supportsSecureCoding {
  277. return YES;
  278. }
  279. - (nullable instancetype)initWithCoder:(NSCoder *)decoder {
  280. self = [super init];
  281. if (self) {
  282. _authenticationHandlerQueue = [[NSMutableArray alloc] init];
  283. _authState = [decoder decodeObjectOfClass:[OIDAuthState class] forKey:kAuthStateKey];
  284. }
  285. return self;
  286. }
  287. - (void)encodeWithCoder:(NSCoder *)encoder {
  288. [encoder encodeObject:_authState forKey:kAuthStateKey];
  289. }
  290. @end
  291. NS_ASSUME_NONNULL_END