GIDAuthentication.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  18. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  19. #import "GoogleSignIn/Sources/GIDMDMPasscodeState.h"
  20. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  21. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDSignIn.h"
  22. #ifdef SWIFT_PACKAGE
  23. @import AppAuth;
  24. #else
  25. #import <AppAuth/OIDAuthState.h>
  26. #import <AppAuth/OIDAuthorizationRequest.h>
  27. #import <AppAuth/OIDAuthorizationResponse.h>
  28. #import <AppAuth/OIDAuthorizationService.h>
  29. #import <AppAuth/OIDError.h>
  30. #import <AppAuth/OIDIDToken.h>
  31. #import <AppAuth/OIDTokenRequest.h>
  32. #import <AppAuth/OIDTokenResponse.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. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  48. // The specialized GTMAppAuthFetcherAuthorization delegate that handles potential EMM error
  49. // responses.
  50. @interface GTMAppAuthFetcherAuthorizationEMMChainedDelegate : NSObject
  51. // Initializes with chained delegate and selector.
  52. - (instancetype)initWithDelegate:(id)delegate selector:(SEL)selector;
  53. // The callback method for GTMAppAuthFetcherAuthorization to invoke.
  54. - (void)authentication:(GTMAppAuthFetcherAuthorization *)auth
  55. request:(NSMutableURLRequest *)request
  56. finishedWithError:(nullable NSError *)error;
  57. @end
  58. @implementation GTMAppAuthFetcherAuthorizationEMMChainedDelegate {
  59. // We use a weak reference here to match GTMAppAuthFetcherAuthorization.
  60. __weak id _delegate;
  61. SEL _selector;
  62. // We need to maintain a reference to the chained delegate because GTMAppAuthFetcherAuthorization
  63. // only keeps a weak reference.
  64. GTMAppAuthFetcherAuthorizationEMMChainedDelegate *_retained_self;
  65. }
  66. - (instancetype)initWithDelegate:(id)delegate selector:(SEL)selector {
  67. self = [super init];
  68. if (self) {
  69. _delegate = delegate;
  70. _selector = selector;
  71. _retained_self = self;
  72. }
  73. return self;
  74. }
  75. - (void)authentication:(GTMAppAuthFetcherAuthorization *)auth
  76. request:(NSMutableURLRequest *)request
  77. finishedWithError:(nullable NSError *)error {
  78. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  79. if (!self->_delegate || !self->_selector) {
  80. return;
  81. }
  82. NSMethodSignature *signature = [self->_delegate methodSignatureForSelector:self->_selector];
  83. if (!signature) {
  84. return;
  85. }
  86. id argument1 = auth;
  87. id argument2 = request;
  88. id argument3 = error;
  89. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
  90. [invocation setTarget:self->_delegate]; // index 0
  91. [invocation setSelector:self->_selector]; // index 1
  92. [invocation setArgument:&argument1 atIndex:2];
  93. [invocation setArgument:&argument2 atIndex:3];
  94. [invocation setArgument:&argument3 atIndex:4];
  95. [invocation invoke];
  96. }];
  97. // Prepare to deallocate the chained delegate instance because the above block will retain the
  98. // iVar references it uses.
  99. _retained_self = nil;
  100. }
  101. @end
  102. // A specialized GTMAppAuthFetcherAuthorization subclass with EMM support.
  103. @interface GTMAppAuthFetcherAuthorizationWithEMMSupport : GTMAppAuthFetcherAuthorization
  104. @end
  105. @implementation GTMAppAuthFetcherAuthorizationWithEMMSupport
  106. #pragma clang diagnostic push
  107. #pragma clang diagnostic ignored "-Wdeprecated-implementations"
  108. - (void)authorizeRequest:(nullable NSMutableURLRequest *)request
  109. delegate:(id)delegate
  110. didFinishSelector:(SEL)sel {
  111. #pragma clang diagnostic pop
  112. GTMAppAuthFetcherAuthorizationEMMChainedDelegate *chainedDelegate =
  113. [[GTMAppAuthFetcherAuthorizationEMMChainedDelegate alloc] initWithDelegate:delegate
  114. selector:sel];
  115. #pragma clang diagnostic push
  116. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  117. [super authorizeRequest:request
  118. delegate:chainedDelegate
  119. didFinishSelector:@selector(authentication:request:finishedWithError:)];
  120. #pragma clang diagnostic pop
  121. }
  122. - (void)authorizeRequest:(nullable NSMutableURLRequest *)request
  123. completionHandler:(GTMAppAuthFetcherAuthorizationCompletion)handler {
  124. [super authorizeRequest:request completionHandler:^(NSError *_Nullable error) {
  125. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  126. handler(error);
  127. }];
  128. }];
  129. }
  130. @end
  131. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  132. @implementation GIDAuthentication {
  133. // A queue for pending authentication handlers so we don't fire multiple requests in parallel.
  134. // Access to this ivar should be synchronized.
  135. NSMutableArray *_authenticationHandlerQueue;
  136. }
  137. - (instancetype)initWithAuthState:(OIDAuthState *)authState {
  138. if (!authState) {
  139. return nil;
  140. }
  141. self = [super init];
  142. if (self) {
  143. _authenticationHandlerQueue = [[NSMutableArray alloc] init];
  144. _authState = authState;
  145. }
  146. return self;
  147. }
  148. #pragma mark - Public property accessors
  149. - (NSString *)clientID {
  150. return _authState.lastAuthorizationResponse.request.clientID;
  151. }
  152. - (NSString *)accessToken {
  153. return _authState.lastTokenResponse.accessToken;
  154. }
  155. - (NSDate *)accessTokenExpirationDate {
  156. return _authState.lastTokenResponse.accessTokenExpirationDate;
  157. }
  158. - (NSString *)refreshToken {
  159. return _authState.refreshToken;
  160. }
  161. - (nullable NSString *)idToken {
  162. return _authState.lastTokenResponse.idToken;
  163. }
  164. - (nullable NSDate *)idTokenExpirationDate {
  165. return [[[OIDIDToken alloc] initWithIDTokenString:self.idToken] expiresAt];
  166. }
  167. #pragma mark - Private property accessors
  168. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  169. - (NSString *)emmSupport {
  170. return
  171. _authState.lastAuthorizationResponse.request.additionalParameters[kEMMSupportParameterName];
  172. }
  173. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  174. #pragma mark - Public methods
  175. #pragma clang diagnostic push
  176. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  177. - (id<GTMFetcherAuthorizationProtocol>)fetcherAuthorizer {
  178. #pragma clang diagnostic pop
  179. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  180. GTMAppAuthFetcherAuthorization *authorization = self.emmSupport ?
  181. [[GTMAppAuthFetcherAuthorizationWithEMMSupport alloc] initWithAuthState:_authState] :
  182. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:_authState];
  183. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  184. GTMAppAuthFetcherAuthorization *authorization =
  185. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:_authState];
  186. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  187. authorization.tokenRefreshDelegate = self;
  188. return authorization;
  189. }
  190. - (void)doWithFreshTokens:(GIDAuthenticationCompletion)completion {
  191. if (!([self.accessTokenExpirationDate timeIntervalSinceNow] < kMinimalTimeToExpire ||
  192. (self.idToken && [self.idTokenExpirationDate timeIntervalSinceNow] < kMinimalTimeToExpire))) {
  193. dispatch_async(dispatch_get_main_queue(), ^{
  194. completion(self, nil);
  195. });
  196. return;
  197. }
  198. @synchronized (_authenticationHandlerQueue) {
  199. // Push the handler into the callback queue.
  200. [_authenticationHandlerQueue addObject:[completion copy]];
  201. if (_authenticationHandlerQueue.count > 1) {
  202. // This is not the first handler in the queue, no fetch is needed.
  203. return;
  204. }
  205. }
  206. // This is the first handler in the queue, a fetch is needed.
  207. NSMutableDictionary *additionalParameters = [@{} mutableCopy];
  208. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  209. [additionalParameters addEntriesFromDictionary:
  210. [GIDAuthentication updatedEMMParametersWithParameters:
  211. _authState.lastTokenResponse.request.additionalParameters]];
  212. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  213. [additionalParameters addEntriesFromDictionary:
  214. _authState.lastTokenResponse.request.additionalParameters];
  215. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  216. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  217. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  218. OIDTokenRequest *tokenRefreshRequest =
  219. [_authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  220. [OIDAuthorizationService performTokenRequest:tokenRefreshRequest
  221. originalAuthorizationResponse:_authState.lastAuthorizationResponse
  222. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  223. NSError *_Nullable error) {
  224. if (tokenResponse) {
  225. [self willChangeValueForKey:NSStringFromSelector(@selector(accessToken))];
  226. [self willChangeValueForKey:NSStringFromSelector(@selector(accessTokenExpirationDate))];
  227. [self willChangeValueForKey:NSStringFromSelector(@selector(idToken))];
  228. [self willChangeValueForKey:NSStringFromSelector(@selector(idTokenExpirationDate))];
  229. [self->_authState updateWithTokenResponse:tokenResponse error:nil];
  230. [self didChangeValueForKey:NSStringFromSelector(@selector(accessToken))];
  231. [self didChangeValueForKey:NSStringFromSelector(@selector(accessTokenExpirationDate))];
  232. [self didChangeValueForKey:NSStringFromSelector(@selector(idToken))];
  233. [self didChangeValueForKey:NSStringFromSelector(@selector(idTokenExpirationDate))];
  234. } else {
  235. if (error.domain == OIDOAuthTokenErrorDomain) {
  236. [self->_authState updateWithAuthorizationError:error];
  237. }
  238. }
  239. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  240. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  241. // Process the handler queue to call back.
  242. NSArray *authenticationHandlerQueue;
  243. @synchronized(self->_authenticationHandlerQueue) {
  244. authenticationHandlerQueue = [self->_authenticationHandlerQueue copy];
  245. [self->_authenticationHandlerQueue removeAllObjects];
  246. }
  247. for (GIDAuthenticationCompletion completion in authenticationHandlerQueue) {
  248. dispatch_async(dispatch_get_main_queue(), ^{
  249. completion(error ? nil : self, error);
  250. });
  251. }
  252. }];
  253. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  254. NSArray *authenticationHandlerQueue;
  255. @synchronized(self->_authenticationHandlerQueue) {
  256. authenticationHandlerQueue = [self->_authenticationHandlerQueue copy];
  257. [self->_authenticationHandlerQueue removeAllObjects];
  258. }
  259. for (GIDAuthenticationCompletion completion in authenticationHandlerQueue) {
  260. dispatch_async(dispatch_get_main_queue(), ^{
  261. completion(error ? nil : self, error);
  262. });
  263. }
  264. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  265. }];
  266. }
  267. #pragma mark - Private methods
  268. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  269. + (NSDictionary *)parametersWithParameters:(NSDictionary *)parameters
  270. emmSupport:(nullable NSString *)emmSupport
  271. isPasscodeInfoRequired:(BOOL)isPasscodeInfoRequired {
  272. if (!emmSupport) {
  273. return parameters;
  274. }
  275. NSMutableDictionary *allParameters = [(parameters ?: @{}) mutableCopy];
  276. allParameters[kEMMSupportParameterName] = emmSupport;
  277. UIDevice *device = [UIDevice currentDevice];
  278. NSString *systemName = device.systemName;
  279. if ([systemName isEqualToString:kOldIOSSystemName]) {
  280. systemName = kNewIOSSystemName;
  281. }
  282. allParameters[kEMMOSVersionParameterName] =
  283. [NSString stringWithFormat:@"%@ %@", systemName, device.systemVersion];
  284. if (isPasscodeInfoRequired) {
  285. allParameters[kEMMPasscodeInfoParameterName] = [GIDMDMPasscodeState passcodeState].info;
  286. }
  287. return allParameters;
  288. }
  289. + (NSDictionary *)updatedEMMParametersWithParameters:(NSDictionary *)parameters {
  290. return [self parametersWithParameters:parameters
  291. emmSupport:parameters[kEMMSupportParameterName]
  292. isPasscodeInfoRequired:parameters[kEMMPasscodeInfoParameterName] != nil];
  293. }
  294. + (void)handleTokenFetchEMMError:(nullable NSError *)error
  295. completion:(void (^)(NSError *_Nullable))completion {
  296. NSDictionary *errorJSON = error.userInfo[OIDOAuthErrorResponseErrorKey];
  297. if (errorJSON) {
  298. __block BOOL handled = NO;
  299. handled = [[GIDEMMErrorHandler sharedInstance] handleErrorFromResponse:errorJSON
  300. completion:^() {
  301. if (handled) {
  302. completion([NSError errorWithDomain:kGIDSignInErrorDomain
  303. code:kGIDSignInErrorCodeEMM
  304. userInfo:error.userInfo]);
  305. } else {
  306. completion(error);
  307. }
  308. }];
  309. } else {
  310. completion(error);
  311. }
  312. }
  313. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  314. #pragma mark - GTMAppAuthFetcherAuthorizationTokenRefreshDelegate
  315. - (nullable NSDictionary *)additionalRefreshParameters:
  316. (GTMAppAuthFetcherAuthorization *)authorization {
  317. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  318. return [GIDAuthentication updatedEMMParametersWithParameters:
  319. authorization.authState.lastTokenResponse.request.additionalParameters];
  320. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  321. return authorization.authState.lastTokenResponse.request.additionalParameters;
  322. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  323. }
  324. #pragma mark - NSSecureCoding
  325. + (BOOL)supportsSecureCoding {
  326. return YES;
  327. }
  328. - (nullable instancetype)initWithCoder:(NSCoder *)decoder {
  329. self = [super init];
  330. if (self) {
  331. _authenticationHandlerQueue = [[NSMutableArray alloc] init];
  332. _authState = [decoder decodeObjectOfClass:[OIDAuthState class] forKey:kAuthStateKey];
  333. }
  334. return self;
  335. }
  336. - (void)encodeWithCoder:(NSCoder *)encoder {
  337. [encoder encodeObject:_authState forKey:kAuthStateKey];
  338. }
  339. @end
  340. NS_ASSUME_NONNULL_END