No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AppleAuthManager.m 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. //
  2. // MIT License
  3. //
  4. // Copyright (c) 2019-2020 Daniel Lupiañez Casares
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in all
  14. // copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. // SOFTWARE.
  23. //
  24. #import "AppleAuthManager.h"
  25. #import "AppleAuthSerializer.h"
  26. #pragma mark - AppleAuthManager Implementation
  27. // IOS/TVOS 13.0 | MACOS 10.15
  28. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 || __TV_OS_VERSION_MAX_ALLOWED >= 130000 || __MAC_OS_X_VERSION_MAX_ALLOWED >= 101500
  29. #define AUTHENTICATION_SERVICES_AVAILABLE true
  30. #import <AuthenticationServices/AuthenticationServices.h>
  31. #endif
  32. @interface AppleAuthManager ()
  33. @property (nonatomic, assign) NativeMessageHandlerDelegate mainCallback;
  34. @property (nonatomic, weak) NSOperationQueue *callingOperationQueue;
  35. - (void) sendNativeMessageForDictionary:(NSDictionary *)payloadDictionary forRequestId:(uint)requestId;
  36. - (void) sendNativeMessageForString:(NSString *)payloadString forRequestId:(uint)requestId;
  37. - (NSError *)internalErrorWithCode:(NSInteger)code andMessage:(NSString *)message;
  38. - (void) sendsCredentialStatusInternalErrorWithCode:(NSInteger)code andMessage:(NSString *)message forRequestWithId:(uint)requestId;
  39. - (void) sendsLoginResponseInternalErrorWithCode:(NSInteger)code andMessage:(NSString *)message forRequestWithId:(uint)requestId;
  40. @end
  41. #if AUTHENTICATION_SERVICES_AVAILABLE
  42. API_AVAILABLE(ios(13.0), macos(10.15), tvos(13.0), watchos(6.0))
  43. @interface AppleAuthManager () <ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>
  44. @property (nonatomic, strong) ASAuthorizationAppleIDProvider *appleIdProvider;
  45. @property (nonatomic, strong) ASAuthorizationPasswordProvider *passwordProvider;
  46. @property (nonatomic, strong) NSObject *credentialsRevokedObserver;
  47. @property (nonatomic, strong) NSMutableDictionary<NSValue *, NSNumber *> *authorizationsInProgress;
  48. @end
  49. #endif
  50. @implementation AppleAuthManager
  51. + (instancetype) sharedManager
  52. {
  53. static AppleAuthManager *_defaultManager = nil;
  54. static dispatch_once_t defaultManagerInitialization;
  55. dispatch_once(&defaultManagerInitialization, ^{
  56. _defaultManager = [[AppleAuthManager alloc] init];
  57. });
  58. return _defaultManager;
  59. }
  60. - (instancetype) init
  61. {
  62. self = [super init];
  63. if (self)
  64. {
  65. #if AUTHENTICATION_SERVICES_AVAILABLE
  66. if (@available(iOS 13.0, tvOS 13.0, macOS 10.15, *))
  67. {
  68. _appleIdProvider = [[ASAuthorizationAppleIDProvider alloc] init];
  69. _passwordProvider = [[ASAuthorizationPasswordProvider alloc] init];
  70. _authorizationsInProgress = [NSMutableDictionary dictionary];
  71. }
  72. #endif
  73. }
  74. return self;
  75. }
  76. #pragma mark Public methods
  77. - (void) quickLogin:(uint)requestId withNonce:(NSString *)nonce andState:(NSString *)state
  78. {
  79. #if AUTHENTICATION_SERVICES_AVAILABLE
  80. if (@available(iOS 13.0, tvOS 13.0, macOS 10.15, *))
  81. {
  82. ASAuthorizationAppleIDRequest *appleIDRequest = [[self appleIdProvider] createRequest];
  83. [appleIDRequest setNonce:nonce];
  84. [appleIDRequest setState:state];
  85. ASAuthorizationPasswordRequest *keychainRequest = [[self passwordProvider] createRequest];
  86. ASAuthorizationController *authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[appleIDRequest, keychainRequest]];
  87. [self performAuthorizationRequestsForController:authorizationController withRequestId:requestId];
  88. }
  89. else
  90. {
  91. [self sendsLoginResponseInternalErrorWithCode:-100
  92. andMessage:@"Native AppleAuth is only available from iOS 13.0"
  93. forRequestWithId:requestId];
  94. }
  95. #else
  96. [self sendsLoginResponseInternalErrorWithCode:-100
  97. andMessage:@"Native AppleAuth is only available from iOS 13.0"
  98. forRequestWithId:requestId];
  99. #endif
  100. }
  101. - (void) loginWithAppleId:(uint)requestId withOptions:(AppleAuthManagerLoginOptions)options nonce:(NSString *)nonce andState:(NSString *)state
  102. {
  103. #if AUTHENTICATION_SERVICES_AVAILABLE
  104. if (@available(iOS 13.0, tvOS 13.0, macOS 10.15, *))
  105. {
  106. ASAuthorizationAppleIDRequest *request = [[self appleIdProvider] createRequest];
  107. NSMutableArray *scopes = [NSMutableArray array];
  108. if (options & AppleAuthManagerIncludeName)
  109. [scopes addObject:ASAuthorizationScopeFullName];
  110. if (options & AppleAuthManagerIncludeEmail)
  111. [scopes addObject:ASAuthorizationScopeEmail];
  112. [request setRequestedScopes:[scopes copy]];
  113. [request setNonce:nonce];
  114. [request setState:state];
  115. ASAuthorizationController *authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
  116. [self performAuthorizationRequestsForController:authorizationController withRequestId:requestId];
  117. }
  118. else
  119. {
  120. [self sendsLoginResponseInternalErrorWithCode:-100
  121. andMessage:@"Native AppleAuth is only available from iOS 13.0"
  122. forRequestWithId:requestId];
  123. }
  124. #else
  125. [self sendsLoginResponseInternalErrorWithCode:-100
  126. andMessage:@"Native AppleAuth is only available from iOS 13.0"
  127. forRequestWithId:requestId];
  128. #endif
  129. }
  130. - (void) getCredentialStateForUser:(NSString *)userId withRequestId:(uint)requestId
  131. {
  132. #if AUTHENTICATION_SERVICES_AVAILABLE
  133. if (@available(iOS 13.0, tvOS 13.0, macOS 10.15, *))
  134. {
  135. [[self appleIdProvider] getCredentialStateForUserID:userId completion:^(ASAuthorizationAppleIDProviderCredentialState credentialState, NSError * _Nullable error) {
  136. NSNumber *credentialStateNumber = nil;
  137. NSDictionary *errorDictionary = nil;
  138. if (error)
  139. errorDictionary = [AppleAuthSerializer dictionaryForNSError:error];
  140. else
  141. credentialStateNumber = @(credentialState);
  142. NSDictionary *responseDictionary = [AppleAuthSerializer credentialResponseDictionaryForCredentialState:credentialStateNumber
  143. errorDictionary:errorDictionary];
  144. [self sendNativeMessageForDictionary:responseDictionary forRequestId:requestId];
  145. }];
  146. }
  147. else
  148. {
  149. [self sendsCredentialStatusInternalErrorWithCode:-100
  150. andMessage:@"Native AppleAuth is only available from iOS 13.0"
  151. forRequestWithId:requestId];
  152. }
  153. #else
  154. [self sendsCredentialStatusInternalErrorWithCode:-100
  155. andMessage:@"Native AppleAuth is only available from iOS 13.0"
  156. forRequestWithId:requestId];
  157. #endif
  158. }
  159. - (void) registerCredentialsRevokedCallbackForRequestId:(uint)requestId
  160. {
  161. #if AUTHENTICATION_SERVICES_AVAILABLE
  162. if (@available(iOS 13.0, tvOS 13.0, macOS 10.15, *))
  163. {
  164. if ([self credentialsRevokedObserver])
  165. {
  166. [[NSNotificationCenter defaultCenter] removeObserver:[self credentialsRevokedObserver]];
  167. [self setCredentialsRevokedObserver:nil];
  168. }
  169. if (requestId != 0)
  170. {
  171. NSObject *observer = [[NSNotificationCenter defaultCenter] addObserverForName:ASAuthorizationAppleIDProviderCredentialRevokedNotification
  172. object:nil
  173. queue:nil
  174. usingBlock:^(NSNotification * _Nonnull note) {
  175. [self sendNativeMessageForString:@"Credentials Revoked" forRequestId:requestId];
  176. }];
  177. [self setCredentialsRevokedObserver:observer];
  178. }
  179. }
  180. #endif
  181. }
  182. #pragma mark Private methods
  183. - (void) sendNativeMessageForDictionary:(NSDictionary *)payloadDictionary forRequestId:(uint)requestId
  184. {
  185. NSError *error = nil;
  186. NSData *payloadData = [NSJSONSerialization dataWithJSONObject:payloadDictionary options:0 error:&error];
  187. NSString *payloadString = error ? [NSString stringWithFormat:@"Serialization error %@", [error localizedDescription]] : [[NSString alloc] initWithData:payloadData encoding:NSUTF8StringEncoding];
  188. [self sendNativeMessageForString:payloadString forRequestId:requestId];
  189. }
  190. - (void) sendNativeMessageForString:(NSString *)payloadString forRequestId:(uint)requestId
  191. {
  192. if ([self mainCallback] == NULL)
  193. return;
  194. if ([self callingOperationQueue])
  195. {
  196. [[self callingOperationQueue] addOperationWithBlock:^{
  197. [self mainCallback](requestId, [payloadString UTF8String]);
  198. }];
  199. }
  200. else
  201. {
  202. [self mainCallback](requestId, [payloadString UTF8String]);
  203. }
  204. }
  205. - (NSError *)internalErrorWithCode:(NSInteger)code andMessage:(NSString *)message
  206. {
  207. return [NSError errorWithDomain:@"com.unity.AppleAuth"
  208. code:code
  209. userInfo:@{NSLocalizedDescriptionKey : message}];
  210. }
  211. - (void) sendsCredentialStatusInternalErrorWithCode:(NSInteger)code andMessage:(NSString *)message forRequestWithId:(uint)requestId
  212. {
  213. NSError *customError = [self internalErrorWithCode:code andMessage:message];
  214. NSDictionary *customErrorDictionary = [AppleAuthSerializer dictionaryForNSError:customError];
  215. NSDictionary *responseDictionary = [AppleAuthSerializer credentialResponseDictionaryForCredentialState:nil
  216. errorDictionary:customErrorDictionary];
  217. [self sendNativeMessageForDictionary:responseDictionary forRequestId:requestId];
  218. }
  219. - (void) sendsLoginResponseInternalErrorWithCode:(NSInteger)code andMessage:(NSString *)message forRequestWithId:(uint)requestId
  220. {
  221. NSError *customError = [self internalErrorWithCode:code andMessage:message];
  222. NSDictionary *customErrorDictionary = [AppleAuthSerializer dictionaryForNSError:customError];
  223. NSDictionary *responseDictionary = [AppleAuthSerializer loginResponseDictionaryForAppleIdCredentialDictionary:nil
  224. passwordCredentialDictionary:nil
  225. errorDictionary:customErrorDictionary];
  226. [self sendNativeMessageForDictionary:responseDictionary forRequestId:requestId];
  227. }
  228. #if AUTHENTICATION_SERVICES_AVAILABLE
  229. - (void) performAuthorizationRequestsForController:(ASAuthorizationController *)authorizationController withRequestId:(uint)requestId
  230. API_AVAILABLE(ios(13.0), macos(10.15), tvos(13.0), watchos(6.0))
  231. {
  232. NSValue *authControllerAsKey = [NSValue valueWithNonretainedObject:authorizationController];
  233. [[self authorizationsInProgress] setObject:@(requestId) forKey:authControllerAsKey];
  234. [authorizationController setDelegate:self];
  235. [authorizationController setPresentationContextProvider:self];
  236. [authorizationController performRequests];
  237. }
  238. #pragma mark ASAuthorizationControllerDelegate protocol implementation
  239. - (void) authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization
  240. API_AVAILABLE(ios(13.0), macos(10.15), tvos(13.0), watchos(6.0))
  241. {
  242. NSValue *authControllerAsKey = [NSValue valueWithNonretainedObject:controller];
  243. NSNumber *requestIdNumber = [[self authorizationsInProgress] objectForKey:authControllerAsKey];
  244. if (requestIdNumber)
  245. {
  246. NSDictionary *appleIdCredentialDictionary = nil;
  247. NSDictionary *passwordCredentialDictionary = nil;
  248. if ([[authorization credential] isKindOfClass:[ASAuthorizationAppleIDCredential class]])
  249. {
  250. appleIdCredentialDictionary = [AppleAuthSerializer dictionaryForASAuthorizationAppleIDCredential:(ASAuthorizationAppleIDCredential *)[authorization credential]];
  251. }
  252. else if ([[authorization credential] isKindOfClass:[ASPasswordCredential class]])
  253. {
  254. passwordCredentialDictionary = [AppleAuthSerializer dictionaryForASPasswordCredential:(ASPasswordCredential *)[authorization credential]];
  255. }
  256. NSDictionary *responseDictionary = [AppleAuthSerializer loginResponseDictionaryForAppleIdCredentialDictionary:appleIdCredentialDictionary
  257. passwordCredentialDictionary:passwordCredentialDictionary
  258. errorDictionary:nil];
  259. [self sendNativeMessageForDictionary:responseDictionary forRequestId:[requestIdNumber unsignedIntValue]];
  260. [[self authorizationsInProgress] removeObjectForKey:authControllerAsKey];
  261. }
  262. }
  263. - (void) authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error
  264. API_AVAILABLE(ios(13.0), macos(10.15), tvos(13.0), watchos(6.0))
  265. {
  266. NSValue *authControllerAsKey = [NSValue valueWithNonretainedObject:controller];
  267. NSNumber *requestIdNumber = [[self authorizationsInProgress] objectForKey:authControllerAsKey];
  268. if (requestIdNumber)
  269. {
  270. NSDictionary *errorDictionary = [AppleAuthSerializer dictionaryForNSError:error];
  271. NSDictionary *responseDictionary = [AppleAuthSerializer loginResponseDictionaryForAppleIdCredentialDictionary:nil
  272. passwordCredentialDictionary:nil
  273. errorDictionary:errorDictionary];
  274. [self sendNativeMessageForDictionary:responseDictionary forRequestId:[requestIdNumber unsignedIntValue]];
  275. [[self authorizationsInProgress] removeObjectForKey:authControllerAsKey];
  276. }
  277. }
  278. #pragma mark ASAuthorizationControllerPresentationContextProviding protocol implementation
  279. - (ASPresentationAnchor) presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller
  280. API_AVAILABLE(ios(13.0), macos(10.15), tvos(13.0), watchos(6.0))
  281. {
  282. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 || __TV_OS_VERSION_MAX_ALLOWED >= 130000
  283. return [[[UIApplication sharedApplication] delegate] window];
  284. #elif __MAC_OS_X_VERSION_MAX_ALLOWED >= 101500
  285. return [[NSApplication sharedApplication] mainWindow];
  286. #else
  287. return nil;
  288. #endif
  289. }
  290. #endif
  291. @end
  292. #pragma mark - Native C Calls
  293. bool AppleAuth_IsCurrentPlatformSupported()
  294. {
  295. if (@available(iOS 13.0, tvOS 13.0, macOS 10.15, *))
  296. {
  297. return true;
  298. }
  299. else
  300. {
  301. return false;
  302. }
  303. }
  304. void AppleAuth_SetupNativeMessageHandlerCallback(NativeMessageHandlerDelegate callback)
  305. {
  306. [[AppleAuthManager sharedManager] setMainCallback:callback];
  307. [[AppleAuthManager sharedManager] setCallingOperationQueue: [NSOperationQueue currentQueue]];
  308. }
  309. void AppleAuth_GetCredentialState(uint requestId, const char* userId)
  310. {
  311. [[AppleAuthManager sharedManager] getCredentialStateForUser:[NSString stringWithUTF8String:userId] withRequestId:requestId];
  312. }
  313. void AppleAuth_LoginWithAppleId(uint requestId, int options, const char* _Nullable nonceCStr, const char* _Nullable stateCStr)
  314. {
  315. NSString *nonce = nonceCStr != NULL ? [NSString stringWithUTF8String:nonceCStr] : nil;
  316. NSString *state = stateCStr != NULL ? [NSString stringWithUTF8String:stateCStr] : nil;
  317. [[AppleAuthManager sharedManager] loginWithAppleId:requestId withOptions:options nonce:nonce andState:state];
  318. }
  319. void AppleAuth_QuickLogin(uint requestId, const char* _Nullable nonceCStr, const char* _Nullable stateCStr)
  320. {
  321. NSString *nonce = nonceCStr != NULL ? [NSString stringWithUTF8String:nonceCStr] : nil;
  322. NSString *state = stateCStr != NULL ? [NSString stringWithUTF8String:stateCStr] : nil;
  323. [[AppleAuthManager sharedManager] quickLogin:requestId withNonce:nonce andState:state];
  324. }
  325. void AppleAuth_RegisterCredentialsRevokedCallbackId(uint requestId)
  326. {
  327. [[AppleAuthManager sharedManager] registerCredentialsRevokedCallbackForRequestId:requestId];
  328. }
  329. void AppleAuth_LogMessage(const char* _Nullable messageCStr)
  330. {
  331. NSString *message = messageCStr != NULL ? [NSString stringWithUTF8String:messageCStr] : nil;
  332. NSLog(@"%@", message);
  333. }