GIDAuthentication.m 12 KB

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