GIDAuthentication.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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/GIDAuthentication.h"
  15. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  16. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  17. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  18. #import "GoogleSignIn/Sources/GIDMDMPasscodeState.h"
  19. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  20. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDSignIn.h"
  21. #ifdef SWIFT_PACKAGE
  22. @import AppAuth;
  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. #endif
  33. // Minimal time interval before expiration for the access token or it needs to be refreshed.
  34. NSTimeInterval kMinimalTimeToExpire = 60.0;
  35. // Key constants used for encode and decode.
  36. static NSString *const kAuthStateKey = @"authState";
  37. // Additional parameter names for EMM.
  38. static NSString *const kEMMSupportParameterName = @"emm_support";
  39. static NSString *const kEMMOSVersionParameterName = @"device_os";
  40. static NSString *const kEMMPasscodeInfoParameterName = @"emm_passcode_info";
  41. // Old UIDevice system name for iOS.
  42. static NSString *const kOldIOSSystemName = @"iPhone OS";
  43. // New UIDevice system name for iOS.
  44. static NSString *const kNewIOSSystemName = @"iOS";
  45. NS_ASSUME_NONNULL_BEGIN
  46. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  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 (!self->_delegate || !self->_selector) {
  79. return;
  80. }
  81. NSMethodSignature *signature = [self->_delegate methodSignatureForSelector:self->_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:self->_delegate]; // index 0
  90. [invocation setSelector:self->_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. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  125. @implementation GIDAuthentication {
  126. // A queue for pending authentication handlers so we don't fire multiple requests in parallel.
  127. // Access to this ivar should be synchronized.
  128. NSMutableArray *_authenticationHandlerQueue;
  129. }
  130. - (instancetype)initWithAuthState:(OIDAuthState *)authState {
  131. if (!authState) {
  132. return nil;
  133. }
  134. self = [super init];
  135. if (self) {
  136. _authenticationHandlerQueue = [[NSMutableArray alloc] init];
  137. _authState = authState;
  138. }
  139. return self;
  140. }
  141. #pragma mark - Private property accessors
  142. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  143. - (NSString *)emmSupport {
  144. return
  145. _authState.lastAuthorizationResponse.request.additionalParameters[kEMMSupportParameterName];
  146. }
  147. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  148. #pragma mark - Public methods
  149. - (id<GTMFetcherAuthorizationProtocol>)fetcherAuthorizer {
  150. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  151. GTMAppAuthFetcherAuthorization *authorization = self.emmSupport ?
  152. [[GTMAppAuthFetcherAuthorizationWithEMMSupport alloc] initWithAuthState:_authState] :
  153. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:_authState];
  154. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  155. GTMAppAuthFetcherAuthorization *authorization =
  156. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:_authState];
  157. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  158. authorization.tokenRefreshDelegate = self;
  159. return authorization;
  160. }
  161. - (void)doWithFreshTokens:(GIDAuthenticationCompletion)completion {
  162. NSDate *accessTokenExpirationDate = _authState.lastTokenResponse.accessTokenExpirationDate;
  163. NSString *idToken = _authState.lastTokenResponse.idToken;
  164. NSDate *idTokenExpirationDate = [[[OIDIDToken alloc] initWithIDTokenString:idToken] expiresAt];
  165. if (!([accessTokenExpirationDate timeIntervalSinceNow] < kMinimalTimeToExpire ||
  166. (idToken && [idTokenExpirationDate timeIntervalSinceNow] < kMinimalTimeToExpire))) {
  167. dispatch_async(dispatch_get_main_queue(), ^{
  168. completion(self->_authState, nil);
  169. });
  170. return;
  171. }
  172. @synchronized (_authenticationHandlerQueue) {
  173. // Push the handler into the callback queue.
  174. [_authenticationHandlerQueue addObject:[completion copy]];
  175. if (_authenticationHandlerQueue.count > 1) {
  176. // This is not the first handler in the queue, no fetch is needed.
  177. return;
  178. }
  179. }
  180. // This is the first handler in the queue, a fetch is needed.
  181. NSMutableDictionary *additionalParameters = [@{} mutableCopy];
  182. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  183. [additionalParameters addEntriesFromDictionary:
  184. [GIDAuthentication updatedEMMParametersWithParameters:
  185. _authState.lastTokenResponse.request.additionalParameters]];
  186. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  187. [additionalParameters addEntriesFromDictionary:
  188. _authState.lastTokenResponse.request.additionalParameters];
  189. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  190. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  191. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  192. OIDTokenRequest *tokenRefreshRequest =
  193. [_authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  194. [OIDAuthorizationService performTokenRequest:tokenRefreshRequest
  195. originalAuthorizationResponse:_authState.lastAuthorizationResponse
  196. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  197. NSError *_Nullable error) {
  198. if (tokenResponse) {
  199. [self->_authState updateWithTokenResponse:tokenResponse error:nil];
  200. } else {
  201. if (error.domain == OIDOAuthTokenErrorDomain) {
  202. [self->_authState updateWithAuthorizationError:error];
  203. }
  204. }
  205. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  206. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  207. // Process the handler queue to call back.
  208. NSArray *authenticationHandlerQueue;
  209. @synchronized(self->_authenticationHandlerQueue) {
  210. authenticationHandlerQueue = [self->_authenticationHandlerQueue copy];
  211. [self->_authenticationHandlerQueue removeAllObjects];
  212. }
  213. for (GIDAuthenticationCompletion completion in authenticationHandlerQueue) {
  214. dispatch_async(dispatch_get_main_queue(), ^{
  215. completion(error ? nil : self->_authState, error);
  216. });
  217. }
  218. }];
  219. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  220. NSArray *authenticationHandlerQueue;
  221. @synchronized(self->_authenticationHandlerQueue) {
  222. authenticationHandlerQueue = [self->_authenticationHandlerQueue copy];
  223. [self->_authenticationHandlerQueue removeAllObjects];
  224. }
  225. for (GIDAuthenticationCompletion completion in authenticationHandlerQueue) {
  226. dispatch_async(dispatch_get_main_queue(), ^{
  227. completion(error ? nil : self->_authState, error);
  228. });
  229. }
  230. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  231. }];
  232. }
  233. #pragma mark - Private methods
  234. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  235. + (NSDictionary *)parametersWithParameters:(NSDictionary *)parameters
  236. emmSupport:(nullable NSString *)emmSupport
  237. isPasscodeInfoRequired:(BOOL)isPasscodeInfoRequired {
  238. if (!emmSupport) {
  239. return parameters;
  240. }
  241. NSMutableDictionary *allParameters = [(parameters ?: @{}) mutableCopy];
  242. allParameters[kEMMSupportParameterName] = emmSupport;
  243. UIDevice *device = [UIDevice currentDevice];
  244. NSString *systemName = device.systemName;
  245. if ([systemName isEqualToString:kOldIOSSystemName]) {
  246. systemName = kNewIOSSystemName;
  247. }
  248. allParameters[kEMMOSVersionParameterName] =
  249. [NSString stringWithFormat:@"%@ %@", systemName, device.systemVersion];
  250. if (isPasscodeInfoRequired) {
  251. allParameters[kEMMPasscodeInfoParameterName] = [GIDMDMPasscodeState passcodeState].info;
  252. }
  253. return allParameters;
  254. }
  255. + (NSDictionary *)updatedEMMParametersWithParameters:(NSDictionary *)parameters {
  256. return [self parametersWithParameters:parameters
  257. emmSupport:parameters[kEMMSupportParameterName]
  258. isPasscodeInfoRequired:parameters[kEMMPasscodeInfoParameterName] != nil];
  259. }
  260. + (void)handleTokenFetchEMMError:(nullable NSError *)error
  261. completion:(void (^)(NSError *_Nullable))completion {
  262. NSDictionary *errorJSON = error.userInfo[OIDOAuthErrorResponseErrorKey];
  263. if (errorJSON) {
  264. __block BOOL handled = NO;
  265. handled = [[GIDEMMErrorHandler sharedInstance] handleErrorFromResponse:errorJSON
  266. completion:^() {
  267. if (handled) {
  268. completion([NSError errorWithDomain:kGIDSignInErrorDomain
  269. code:kGIDSignInErrorCodeEMM
  270. userInfo:error.userInfo]);
  271. } else {
  272. completion(error);
  273. }
  274. }];
  275. } else {
  276. completion(error);
  277. }
  278. }
  279. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  280. #pragma mark - GTMAppAuthFetcherAuthorizationTokenRefreshDelegate
  281. - (nullable NSDictionary *)additionalRefreshParameters:
  282. (GTMAppAuthFetcherAuthorization *)authorization {
  283. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  284. return [GIDAuthentication updatedEMMParametersWithParameters:
  285. authorization.authState.lastTokenResponse.request.additionalParameters];
  286. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  287. return authorization.authState.lastTokenResponse.request.additionalParameters;
  288. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  289. }
  290. #pragma mark - NSSecureCoding
  291. + (BOOL)supportsSecureCoding {
  292. return YES;
  293. }
  294. - (nullable instancetype)initWithCoder:(NSCoder *)decoder {
  295. self = [super init];
  296. if (self) {
  297. _authenticationHandlerQueue = [[NSMutableArray alloc] init];
  298. _authState = [decoder decodeObjectOfClass:[OIDAuthState class] forKey:kAuthStateKey];
  299. }
  300. return self;
  301. }
  302. - (void)encodeWithCoder:(NSCoder *)encoder {
  303. [encoder encodeObject:_authState forKey:kAuthStateKey];
  304. }
  305. @end
  306. NS_ASSUME_NONNULL_END