GIDAuthentication.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. #if TARGET_OS_IOS
  199. OIDTokenRequest *tokenRefreshRequest =
  200. [_authState tokenRefreshRequestWithAdditionalParameters:
  201. [GIDAuthentication updatedEMMParametersWithParameters:
  202. _authState.lastTokenResponse.request.additionalParameters]];
  203. #else // TARGET_OS_OSX or TARGET_OS_MACCATALYST
  204. OIDTokenRequest *tokenRefreshRequest =
  205. [_authState tokenRefreshRequestWithAdditionalParameters:
  206. _authState.lastTokenResponse.request.additionalParameters];
  207. #endif
  208. [OIDAuthorizationService performTokenRequest:tokenRefreshRequest
  209. originalAuthorizationResponse:_authState.lastAuthorizationResponse
  210. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  211. NSError *_Nullable error) {
  212. if (tokenResponse) {
  213. [self willChangeValueForKey:NSStringFromSelector(@selector(accessToken))];
  214. [self willChangeValueForKey:NSStringFromSelector(@selector(accessTokenExpirationDate))];
  215. [self willChangeValueForKey:NSStringFromSelector(@selector(idToken))];
  216. [self willChangeValueForKey:NSStringFromSelector(@selector(idTokenExpirationDate))];
  217. [self->_authState updateWithTokenResponse:tokenResponse error:nil];
  218. [self didChangeValueForKey:NSStringFromSelector(@selector(accessToken))];
  219. [self didChangeValueForKey:NSStringFromSelector(@selector(accessTokenExpirationDate))];
  220. [self didChangeValueForKey:NSStringFromSelector(@selector(idToken))];
  221. [self didChangeValueForKey:NSStringFromSelector(@selector(idTokenExpirationDate))];
  222. } else {
  223. if (error.domain == OIDOAuthTokenErrorDomain) {
  224. [self->_authState updateWithAuthorizationError:error];
  225. }
  226. }
  227. #if TARGET_OS_IOS
  228. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  229. // Process the handler queue to call back.
  230. NSArray *authenticationHandlerQueue;
  231. @synchronized(self->_authenticationHandlerQueue) {
  232. authenticationHandlerQueue = [self->_authenticationHandlerQueue copy];
  233. [self->_authenticationHandlerQueue removeAllObjects];
  234. }
  235. for (GIDAuthenticationAction action in authenticationHandlerQueue) {
  236. dispatch_async(dispatch_get_main_queue(), ^{
  237. action(error ? nil : self, error);
  238. });
  239. }
  240. }];
  241. #else // TARGET_OS_OSX or TARGET_OS_MACCATALYST
  242. NSArray *authenticationHandlerQueue;
  243. @synchronized(self->_authenticationHandlerQueue) {
  244. authenticationHandlerQueue = [self->_authenticationHandlerQueue copy];
  245. [self->_authenticationHandlerQueue removeAllObjects];
  246. }
  247. for (GIDAuthenticationAction action in authenticationHandlerQueue) {
  248. dispatch_async(dispatch_get_main_queue(), ^{
  249. action(error ? nil : self, error);
  250. });
  251. }
  252. #endif
  253. }];
  254. }
  255. #pragma mark - Private methods
  256. #if TARGET_OS_IOS
  257. + (NSDictionary *)parametersWithParameters:(NSDictionary *)parameters
  258. emmSupport:(nullable NSString *)emmSupport
  259. isPasscodeInfoRequired:(BOOL)isPasscodeInfoRequired {
  260. if (!emmSupport) {
  261. return parameters;
  262. }
  263. NSMutableDictionary *allParameters = [(parameters ?: @{}) mutableCopy];
  264. allParameters[kEMMSupportParameterName] = emmSupport;
  265. UIDevice *device = [UIDevice currentDevice];
  266. NSString *systemName = device.systemName;
  267. if ([systemName isEqualToString:kOldIOSSystemName]) {
  268. systemName = kNewIOSSystemName;
  269. }
  270. allParameters[kEMMOSVersionParameterName] =
  271. [NSString stringWithFormat:@"%@ %@", systemName, device.systemVersion];
  272. if (isPasscodeInfoRequired) {
  273. allParameters[kEMMPasscodeInfoParameterName] = [GIDMDMPasscodeState passcodeState].info;
  274. }
  275. allParameters[kSDKVersionLoggingParameter] = GIDVersion();
  276. return allParameters;
  277. }
  278. + (NSDictionary *)updatedEMMParametersWithParameters:(NSDictionary *)parameters {
  279. return [self parametersWithParameters:parameters
  280. emmSupport:parameters[kEMMSupportParameterName]
  281. isPasscodeInfoRequired:parameters[kEMMPasscodeInfoParameterName] != nil];
  282. }
  283. + (void)handleTokenFetchEMMError:(nullable NSError *)error
  284. completion:(void (^)(NSError *_Nullable))completion {
  285. NSDictionary *errorJSON = error.userInfo[OIDOAuthErrorResponseErrorKey];
  286. if (errorJSON) {
  287. __block BOOL handled = NO;
  288. handled = [[GIDEMMErrorHandler sharedInstance] handleErrorFromResponse:errorJSON
  289. completion:^() {
  290. if (handled) {
  291. completion([NSError errorWithDomain:kGIDSignInErrorDomain
  292. code:kGIDSignInErrorCodeEMM
  293. userInfo:error.userInfo]);
  294. } else {
  295. completion(error);
  296. }
  297. }];
  298. } else {
  299. completion(error);
  300. }
  301. }
  302. #endif
  303. #pragma mark - GTMAppAuthFetcherAuthorizationTokenRefreshDelegate
  304. - (nullable NSDictionary *)additionalRefreshParameters:
  305. (GTMAppAuthFetcherAuthorization *)authorization {
  306. #if TARGET_OS_IOS
  307. return [GIDAuthentication updatedEMMParametersWithParameters:
  308. authorization.authState.lastTokenResponse.request.additionalParameters];
  309. #else // TARGET_OS_MACCATALYST or TARGET_OS_OSX
  310. return authorization.authState.lastTokenResponse.request.additionalParameters;
  311. #endif
  312. }
  313. #pragma mark - NSSecureCoding
  314. + (BOOL)supportsSecureCoding {
  315. return YES;
  316. }
  317. - (nullable instancetype)initWithCoder:(NSCoder *)decoder {
  318. self = [super init];
  319. if (self) {
  320. _authenticationHandlerQueue = [[NSMutableArray alloc] init];
  321. _authState = [decoder decodeObjectOfClass:[OIDAuthState class] forKey:kAuthStateKey];
  322. }
  323. return self;
  324. }
  325. - (void)encodeWithCoder:(NSCoder *)encoder {
  326. [encoder encodeObject:_authState forKey:kAuthStateKey];
  327. }
  328. @end
  329. NS_ASSUME_NONNULL_END