GIDAuthentication.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. #else
  23. #import <AppAuth/OIDAuthState.h>
  24. #import <AppAuth/OIDAuthorizationRequest.h>
  25. #import <AppAuth/OIDAuthorizationResponse.h>
  26. #import <AppAuth/OIDAuthorizationService.h>
  27. #import <AppAuth/OIDError.h>
  28. #import <AppAuth/OIDIDToken.h>
  29. #import <AppAuth/OIDTokenRequest.h>
  30. #import <AppAuth/OIDTokenResponse.h>
  31. #endif
  32. NS_ASSUME_NONNULL_BEGIN
  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. // The specialized GTMAppAuthFetcherAuthorization delegate that handles potential EMM error
  46. // responses.
  47. @interface GTMAppAuthFetcherAuthorizationEMMChainedDelegate : NSObject
  48. // Initializes with chained delegate and selector.
  49. - (instancetype)initWithDelegate:(id)delegate selector:(SEL)selector;
  50. // The callback method for GTMAppAuthFetcherAuthorization to invoke.
  51. - (void)authentication:(GTMAppAuthFetcherAuthorization *)auth
  52. request:(NSMutableURLRequest *)request
  53. finishedWithError:(nullable NSError *)error;
  54. @end
  55. @implementation GTMAppAuthFetcherAuthorizationEMMChainedDelegate {
  56. // We use a weak reference here to match GTMAppAuthFetcherAuthorization.
  57. __weak id _delegate;
  58. SEL _selector;
  59. // We need to maintain a reference to the chained delegate because GTMAppAuthFetcherAuthorization
  60. // only keeps a weak reference.
  61. GTMAppAuthFetcherAuthorizationEMMChainedDelegate *_retained_self;
  62. }
  63. - (instancetype)initWithDelegate:(id)delegate selector:(SEL)selector {
  64. self = [super init];
  65. if (self) {
  66. _delegate = delegate;
  67. _selector = selector;
  68. _retained_self = self;
  69. }
  70. return self;
  71. }
  72. - (void)authentication:(GTMAppAuthFetcherAuthorization *)auth
  73. request:(NSMutableURLRequest *)request
  74. finishedWithError:(nullable NSError *)error {
  75. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  76. if (!self->_delegate || !self->_selector) {
  77. return;
  78. }
  79. NSMethodSignature *signature = [self->_delegate methodSignatureForSelector:self->_selector];
  80. if (!signature) {
  81. return;
  82. }
  83. id argument1 = auth;
  84. id argument2 = request;
  85. id argument3 = error;
  86. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
  87. [invocation setTarget:self->_delegate]; // index 0
  88. [invocation setSelector:self->_selector]; // index 1
  89. [invocation setArgument:&argument1 atIndex:2];
  90. [invocation setArgument:&argument2 atIndex:3];
  91. [invocation setArgument:&argument3 atIndex:4];
  92. [invocation invoke];
  93. }];
  94. // Prepare to deallocate the chained delegate instance because the above block will retain the
  95. // iVar references it uses.
  96. _retained_self = nil;
  97. }
  98. @end
  99. // A specialized GTMAppAuthFetcherAuthorization subclass with EMM support.
  100. @interface GTMAppAuthFetcherAuthorizationWithEMMSupport : GTMAppAuthFetcherAuthorization
  101. @end
  102. @implementation GTMAppAuthFetcherAuthorizationWithEMMSupport
  103. - (void)authorizeRequest:(nullable NSMutableURLRequest *)request
  104. delegate:(id)delegate
  105. didFinishSelector:(SEL)sel {
  106. GTMAppAuthFetcherAuthorizationEMMChainedDelegate *chainedDelegate =
  107. [[GTMAppAuthFetcherAuthorizationEMMChainedDelegate alloc] initWithDelegate:delegate
  108. selector:sel];
  109. [super authorizeRequest:request
  110. delegate:chainedDelegate
  111. didFinishSelector:@selector(authentication:request:finishedWithError:)];
  112. }
  113. - (void)authorizeRequest:(nullable NSMutableURLRequest *)request
  114. completionHandler:(GTMAppAuthFetcherAuthorizationCompletion)handler {
  115. [super authorizeRequest:request completionHandler:^(NSError *_Nullable error) {
  116. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  117. handler(error);
  118. }];
  119. }];
  120. }
  121. @end
  122. @implementation GIDAuthentication {
  123. // A queue for pending authentication handlers so we don't fire multiple requests in parallel.
  124. // Access to this ivar should be synchronized.
  125. NSMutableArray *_authenticationHandlerQueue;
  126. }
  127. - (instancetype)initWithAuthState:(OIDAuthState *)authState {
  128. if (!authState) {
  129. return nil;
  130. }
  131. self = [super init];
  132. if (self) {
  133. _authenticationHandlerQueue = [[NSMutableArray alloc] init];
  134. _authState = authState;
  135. }
  136. return self;
  137. }
  138. #pragma mark - Public property accessors
  139. - (NSString *)clientID {
  140. return _authState.lastAuthorizationResponse.request.clientID;
  141. }
  142. - (NSString *)accessToken {
  143. return _authState.lastTokenResponse.accessToken;
  144. }
  145. - (NSDate *)accessTokenExpirationDate {
  146. return _authState.lastTokenResponse.accessTokenExpirationDate;
  147. }
  148. - (NSString *)refreshToken {
  149. return _authState.refreshToken;
  150. }
  151. - (nullable NSString *)idToken {
  152. return _authState.lastTokenResponse.idToken;
  153. }
  154. - (nullable NSDate *)idTokenExpirationDate {
  155. return [[[OIDIDToken alloc] initWithIDTokenString:self.idToken] expiresAt];
  156. }
  157. #pragma mark - Private property accessors
  158. - (NSString *)emmSupport {
  159. return
  160. _authState.lastAuthorizationResponse.request.additionalParameters[kEMMSupportParameterName];
  161. }
  162. #pragma mark - Public methods
  163. - (id<GTMFetcherAuthorizationProtocol>)fetcherAuthorizer {
  164. GTMAppAuthFetcherAuthorization *authorization = self.emmSupport ?
  165. [[GTMAppAuthFetcherAuthorizationWithEMMSupport alloc] initWithAuthState:_authState] :
  166. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:_authState];
  167. authorization.tokenRefreshDelegate = self;
  168. return authorization;
  169. }
  170. - (void)doWithFreshTokens:(GIDAuthenticationAction)action {
  171. if (!([self.accessTokenExpirationDate timeIntervalSinceNow] < kMinimalTimeToExpire ||
  172. (self.idToken && [self.idTokenExpirationDate timeIntervalSinceNow] < kMinimalTimeToExpire))) {
  173. dispatch_async(dispatch_get_main_queue(), ^{
  174. action(self, nil);
  175. });
  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. [self->_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. [self->_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(self->_authenticationHandlerQueue) {
  214. authenticationHandlerQueue = [self->_authenticationHandlerQueue copy];
  215. [self->_authenticationHandlerQueue removeAllObjects];
  216. }
  217. for (GIDAuthenticationAction action in authenticationHandlerQueue) {
  218. dispatch_async(dispatch_get_main_queue(), ^{
  219. action(error ? nil : self, error);
  220. });
  221. }
  222. }];
  223. }];
  224. }
  225. #pragma mark - Private methods
  226. + (NSDictionary *)parametersWithParameters:(NSDictionary *)parameters
  227. emmSupport:(nullable NSString *)emmSupport
  228. isPasscodeInfoRequired:(BOOL)isPasscodeInfoRequired {
  229. if (!emmSupport) {
  230. return parameters;
  231. }
  232. NSMutableDictionary *allParameters = [(parameters ?: @{}) mutableCopy];
  233. allParameters[kEMMSupportParameterName] = emmSupport;
  234. UIDevice *device = [UIDevice currentDevice];
  235. NSString *systemName = device.systemName;
  236. if ([systemName isEqualToString:kOldIOSSystemName]) {
  237. systemName = kNewIOSSystemName;
  238. }
  239. allParameters[kEMMOSVersionParameterName] =
  240. [NSString stringWithFormat:@"%@ %@", systemName, device.systemVersion];
  241. if (isPasscodeInfoRequired) {
  242. allParameters[kEMMPasscodeInfoParameterName] = [GIDMDMPasscodeState passcodeState].info;
  243. }
  244. allParameters[kSDKVersionLoggingParameter] = GIDVersion();
  245. return allParameters;
  246. }
  247. + (NSDictionary *)updatedEMMParametersWithParameters:(NSDictionary *)parameters {
  248. return [self parametersWithParameters:parameters
  249. emmSupport:parameters[kEMMSupportParameterName]
  250. isPasscodeInfoRequired:parameters[kEMMPasscodeInfoParameterName] != nil];
  251. }
  252. + (void)handleTokenFetchEMMError:(nullable NSError *)error
  253. completion:(void (^)(NSError *_Nullable))completion {
  254. NSDictionary *errorJSON = error.userInfo[OIDOAuthErrorResponseErrorKey];
  255. if (errorJSON) {
  256. __block BOOL handled = NO;
  257. handled = [[GIDEMMErrorHandler sharedInstance] handleErrorFromResponse:errorJSON
  258. completion:^() {
  259. if (handled) {
  260. completion([NSError errorWithDomain:kGIDSignInErrorDomain
  261. code:kGIDSignInErrorCodeEMM
  262. userInfo:error.userInfo]);
  263. } else {
  264. completion(error);
  265. }
  266. }];
  267. } else {
  268. completion(error);
  269. }
  270. }
  271. #pragma mark - GTMAppAuthFetcherAuthorizationTokenRefreshDelegate
  272. - (nullable NSDictionary *)additionalRefreshParameters:
  273. (GTMAppAuthFetcherAuthorization *)authorization {
  274. return [GIDAuthentication updatedEMMParametersWithParameters:
  275. authorization.authState.lastTokenResponse.request.additionalParameters];
  276. }
  277. #pragma mark - NSSecureCoding
  278. + (BOOL)supportsSecureCoding {
  279. return YES;
  280. }
  281. - (nullable instancetype)initWithCoder:(NSCoder *)decoder {
  282. self = [super init];
  283. if (self) {
  284. _authenticationHandlerQueue = [[NSMutableArray alloc] init];
  285. _authState = [decoder decodeObjectOfClass:[OIDAuthState class] forKey:kAuthStateKey];
  286. }
  287. return self;
  288. }
  289. - (void)encodeWithCoder:(NSCoder *)encoder {
  290. [encoder encodeObject:_authState forKey:kAuthStateKey];
  291. }
  292. @end
  293. NS_ASSUME_NONNULL_END