GIDAuthentication.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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
  18. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  19. #import "GoogleSignIn/Sources/GIDMDMPasscodeState.h"
  20. #endif
  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
  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. - (void)authorizeRequest:(nullable NSMutableURLRequest *)request
  107. delegate:(id)delegate
  108. didFinishSelector:(SEL)sel {
  109. GTMAppAuthFetcherAuthorizationEMMChainedDelegate *chainedDelegate =
  110. [[GTMAppAuthFetcherAuthorizationEMMChainedDelegate alloc] initWithDelegate:delegate
  111. selector:sel];
  112. [super authorizeRequest:request
  113. delegate:chainedDelegate
  114. didFinishSelector:@selector(authentication:request:finishedWithError:)];
  115. }
  116. - (void)authorizeRequest:(nullable NSMutableURLRequest *)request
  117. completionHandler:(GTMAppAuthFetcherAuthorizationCompletion)handler {
  118. [super authorizeRequest:request completionHandler:^(NSError *_Nullable error) {
  119. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  120. handler(error);
  121. }];
  122. }];
  123. }
  124. @end
  125. #endif
  126. @implementation GIDAuthentication {
  127. // A queue for pending authentication handlers so we don't fire multiple requests in parallel.
  128. // Access to this ivar should be synchronized.
  129. NSMutableArray *_authenticationHandlerQueue;
  130. }
  131. - (instancetype)initWithAuthState:(OIDAuthState *)authState {
  132. if (!authState) {
  133. return nil;
  134. }
  135. self = [super init];
  136. if (self) {
  137. _authenticationHandlerQueue = [[NSMutableArray alloc] init];
  138. _authState = authState;
  139. }
  140. return self;
  141. }
  142. #pragma mark - Public property accessors
  143. - (NSString *)clientID {
  144. return _authState.lastAuthorizationResponse.request.clientID;
  145. }
  146. - (NSString *)accessToken {
  147. return _authState.lastTokenResponse.accessToken;
  148. }
  149. - (NSDate *)accessTokenExpirationDate {
  150. return _authState.lastTokenResponse.accessTokenExpirationDate;
  151. }
  152. - (NSString *)refreshToken {
  153. return _authState.refreshToken;
  154. }
  155. - (nullable NSString *)idToken {
  156. return _authState.lastTokenResponse.idToken;
  157. }
  158. - (nullable NSDate *)idTokenExpirationDate {
  159. return [[[OIDIDToken alloc] initWithIDTokenString:self.idToken] expiresAt];
  160. }
  161. #pragma mark - Private property accessors
  162. #if TARGET_OS_IOS
  163. - (NSString *)emmSupport {
  164. return
  165. _authState.lastAuthorizationResponse.request.additionalParameters[kEMMSupportParameterName];
  166. }
  167. #endif
  168. #pragma mark - Public methods
  169. - (id<GTMFetcherAuthorizationProtocol>)fetcherAuthorizer {
  170. #if TARGET_OS_IOS
  171. GTMAppAuthFetcherAuthorization *authorization = self.emmSupport ?
  172. [[GTMAppAuthFetcherAuthorizationWithEMMSupport alloc] initWithAuthState:_authState] :
  173. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:_authState];
  174. #else // TARGET_OS_OSX or TARGET_OS_MACCATALYST
  175. GTMAppAuthFetcherAuthorization *authorization =
  176. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:_authState];
  177. #endif
  178. authorization.tokenRefreshDelegate = self;
  179. return authorization;
  180. }
  181. - (void)doWithFreshTokens:(GIDAuthenticationAction)action {
  182. if (!([self.accessTokenExpirationDate timeIntervalSinceNow] < kMinimalTimeToExpire ||
  183. (self.idToken && [self.idTokenExpirationDate timeIntervalSinceNow] < kMinimalTimeToExpire))) {
  184. dispatch_async(dispatch_get_main_queue(), ^{
  185. action(self, nil);
  186. });
  187. return;
  188. }
  189. @synchronized (_authenticationHandlerQueue) {
  190. // Push the handler into the callback queue.
  191. [_authenticationHandlerQueue addObject:[action copy]];
  192. if (_authenticationHandlerQueue.count > 1) {
  193. // This is not the first handler in the queue, no fetch is needed.
  194. return;
  195. }
  196. }
  197. // This is the first handler in the queue, a fetch is needed.
  198. NSMutableDictionary *additionalParameters = [@{} mutableCopy];
  199. #if TARGET_OS_IOS
  200. [additionalParameters addEntriesFromDictionary:
  201. [GIDAuthentication updatedEMMParametersWithParameters:
  202. _authState.lastTokenResponse.request.additionalParameters]];
  203. #else // TARGET_OS_OSX or TARGET_OS_MACCATALYST
  204. [additionalParameters addEntriesFromDictionary:
  205. _authState.lastTokenResponse.request.additionalParameters];
  206. #endif
  207. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  208. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  209. OIDTokenRequest *tokenRefreshRequest =
  210. [_authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  211. [OIDAuthorizationService performTokenRequest:tokenRefreshRequest
  212. originalAuthorizationResponse:_authState.lastAuthorizationResponse
  213. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  214. NSError *_Nullable error) {
  215. if (tokenResponse) {
  216. [self willChangeValueForKey:NSStringFromSelector(@selector(accessToken))];
  217. [self willChangeValueForKey:NSStringFromSelector(@selector(accessTokenExpirationDate))];
  218. [self willChangeValueForKey:NSStringFromSelector(@selector(idToken))];
  219. [self willChangeValueForKey:NSStringFromSelector(@selector(idTokenExpirationDate))];
  220. [self->_authState updateWithTokenResponse:tokenResponse error:nil];
  221. [self didChangeValueForKey:NSStringFromSelector(@selector(accessToken))];
  222. [self didChangeValueForKey:NSStringFromSelector(@selector(accessTokenExpirationDate))];
  223. [self didChangeValueForKey:NSStringFromSelector(@selector(idToken))];
  224. [self didChangeValueForKey:NSStringFromSelector(@selector(idTokenExpirationDate))];
  225. } else {
  226. if (error.domain == OIDOAuthTokenErrorDomain) {
  227. [self->_authState updateWithAuthorizationError:error];
  228. }
  229. }
  230. #if TARGET_OS_IOS
  231. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  232. // Process the handler queue to call back.
  233. NSArray *authenticationHandlerQueue;
  234. @synchronized(self->_authenticationHandlerQueue) {
  235. authenticationHandlerQueue = [self->_authenticationHandlerQueue copy];
  236. [self->_authenticationHandlerQueue removeAllObjects];
  237. }
  238. for (GIDAuthenticationAction action in authenticationHandlerQueue) {
  239. dispatch_async(dispatch_get_main_queue(), ^{
  240. action(error ? nil : self, error);
  241. });
  242. }
  243. }];
  244. #else // TARGET_OS_OSX or TARGET_OS_MACCATALYST
  245. NSArray *authenticationHandlerQueue;
  246. @synchronized(self->_authenticationHandlerQueue) {
  247. authenticationHandlerQueue = [self->_authenticationHandlerQueue copy];
  248. [self->_authenticationHandlerQueue removeAllObjects];
  249. }
  250. for (GIDAuthenticationAction action in authenticationHandlerQueue) {
  251. dispatch_async(dispatch_get_main_queue(), ^{
  252. action(error ? nil : self, error);
  253. });
  254. }
  255. #endif
  256. }];
  257. }
  258. #pragma mark - Private methods
  259. #if TARGET_OS_IOS
  260. + (NSDictionary *)parametersWithParameters:(NSDictionary *)parameters
  261. emmSupport:(nullable NSString *)emmSupport
  262. isPasscodeInfoRequired:(BOOL)isPasscodeInfoRequired {
  263. if (!emmSupport) {
  264. return parameters;
  265. }
  266. NSMutableDictionary *allParameters = [(parameters ?: @{}) mutableCopy];
  267. allParameters[kEMMSupportParameterName] = emmSupport;
  268. UIDevice *device = [UIDevice currentDevice];
  269. NSString *systemName = device.systemName;
  270. if ([systemName isEqualToString:kOldIOSSystemName]) {
  271. systemName = kNewIOSSystemName;
  272. }
  273. allParameters[kEMMOSVersionParameterName] =
  274. [NSString stringWithFormat:@"%@ %@", systemName, device.systemVersion];
  275. if (isPasscodeInfoRequired) {
  276. allParameters[kEMMPasscodeInfoParameterName] = [GIDMDMPasscodeState passcodeState].info;
  277. }
  278. return allParameters;
  279. }
  280. + (NSDictionary *)updatedEMMParametersWithParameters:(NSDictionary *)parameters {
  281. return [self parametersWithParameters:parameters
  282. emmSupport:parameters[kEMMSupportParameterName]
  283. isPasscodeInfoRequired:parameters[kEMMPasscodeInfoParameterName] != nil];
  284. }
  285. + (void)handleTokenFetchEMMError:(nullable NSError *)error
  286. completion:(void (^)(NSError *_Nullable))completion {
  287. NSDictionary *errorJSON = error.userInfo[OIDOAuthErrorResponseErrorKey];
  288. if (errorJSON) {
  289. __block BOOL handled = NO;
  290. handled = [[GIDEMMErrorHandler sharedInstance] handleErrorFromResponse:errorJSON
  291. completion:^() {
  292. if (handled) {
  293. completion([NSError errorWithDomain:kGIDSignInErrorDomain
  294. code:kGIDSignInErrorCodeEMM
  295. userInfo:error.userInfo]);
  296. } else {
  297. completion(error);
  298. }
  299. }];
  300. } else {
  301. completion(error);
  302. }
  303. }
  304. #endif
  305. #pragma mark - GTMAppAuthFetcherAuthorizationTokenRefreshDelegate
  306. - (nullable NSDictionary *)additionalRefreshParameters:
  307. (GTMAppAuthFetcherAuthorization *)authorization {
  308. #if TARGET_OS_IOS
  309. return [GIDAuthentication updatedEMMParametersWithParameters:
  310. authorization.authState.lastTokenResponse.request.additionalParameters];
  311. #else // TARGET_OS_MACCATALYST or TARGET_OS_OSX
  312. return authorization.authState.lastTokenResponse.request.additionalParameters;
  313. #endif
  314. }
  315. #pragma mark - NSSecureCoding
  316. + (BOOL)supportsSecureCoding {
  317. return YES;
  318. }
  319. - (nullable instancetype)initWithCoder:(NSCoder *)decoder {
  320. self = [super init];
  321. if (self) {
  322. _authenticationHandlerQueue = [[NSMutableArray alloc] init];
  323. _authState = [decoder decodeObjectOfClass:[OIDAuthState class] forKey:kAuthStateKey];
  324. }
  325. return self;
  326. }
  327. - (void)encodeWithCoder:(NSCoder *)encoder {
  328. [encoder encodeObject:_authState forKey:kAuthStateKey];
  329. }
  330. @end
  331. NS_ASSUME_NONNULL_END