Apple을 사용하여 인증

Firebase SDK를 통해 엔드 투 엔드 OAuth 2.0 로그인 과정을 실행하여 사용자가 Apple ID를 사용해 Firebase에 인증하도록 할 수 있습니다.

시작하기 전에

사용자가 Apple 계정을 통해 로그인하도록 하려면 우선 Apple의 개발자 사이트에서 Apple로 로그인을 구성하고 Firebase 프로젝트에서 로그인 제공업체를 Apple로 사용 설정합니다.

Apple Developer Program에 가입

Apple로 로그인은 Apple Developer Program의 멤버만 구성할 수 있습니다.

Apple로 로그인 구성

  1. Apple 개발자 사이트의 Certificates, Identifiers & Profiles(인증서, 식별자, 프로필) 페이지에서 앱에 Apple로 로그인을 사용 설정합니다.
  2. 웹용 Apple로 로그인 구성의 첫 번째 섹션에 설명된 대로 웹사이트를 앱에 연결합니다. 메시지가 표시되면 다음 URL을 반환 URL로 등록합니다.
    https://YOUR_FIREBASE_PROJECT_ID.firebaseapp.com/__/auth/handler
    Firebase 프로젝트 ID는 Firebase Console 설정 페이지에서 확인할 수 있습니다. 완료했으면 새 서비스 ID를 기록해 둡니다. 이 ID는 다음 섹션에서도 필요합니다.
  3. Apple 비공개 키로 로그인을 생성합니다. 다음 섹션에서는 새로운 비공개 키와 키 ID가 필요합니다.
  4. 이메일 링크 로그인, 이메일 주소 인증, 계정 변경 취소 등 사용자에게 이메일을 보내는 Firebase 인증의 기능 중 하나라도 사용한다면 Apple에서 Firebase 인증을 통해 전송된 이메일을 익명 처리된 Apple 이메일 주소로 전달할 수 있도록 Apple 비공개 이메일 릴레이 서비스를 구성하고 noreply@YOUR_FIREBASE_PROJECT_ID.firebaseapp.com(또는 맞춤설정된 이메일 템플릿 도메인)을 등록해야 합니다.

Apple을 로그인 제공업체로 사용 설정

  1. Apple 프로젝트에 Firebase를 추가합니다. Firebase Console에서 앱을 설정할 때 앱의 번들 ID를 등록해야 합니다.
  2. Firebase Console에서 인증 섹션을 엽니다. 로그인 방법 탭에서 Apple 제공업체를 사용 설정합니다. 이전 섹션에서 만든 서비스 ID를 지정합니다. OAuth 코드 흐름 구성 섹션에서도 Apple 팀 ID외에 이전 섹션에서 만든 비공개 키 및 키 ID를 지정합니다.

Apple의 익명 처리된 데이터 요구사항 준수

Apple로 로그인에는 사용자가 로그인할 때 이메일 주소 등의 데이터를 익명처리할 수 있는 옵션이 제공됩니다. 이 옵션을 선택한 사용자는 privaterelay.appleid.com 도메인의 이메일 주소를 갖게 됩니다. 앱에서 Apple로 로그인을 사용하는 경우 이 익명처리된 Apple ID에 대한 Apple의 관련 개발자 정책 또는 약관을 모두 준수해야 합니다.

또한 개인 식별 정보를 익명처리된 Apple ID와 연결하려면 먼저 사용자 동의를 받아야 합니다. Firebase 인증 사용에는 다음 작업이 포함될 수 있습니다.

  • 이메일 주소와 익명처리된 Apple ID 연결
  • 전화번호와 익명처리된 Apple ID 연결
  • 익명처리되지 않은 소셜 사용자 인증 정보(Facebook, Google 등)와 익명처리된 Apple ID 연결

위 목록은 추후 변경되거나 추가될 수 있습니다. 개발자 계정의 Membership(멤버십) 섹션에서 Apple Developer Program License Agreement(Apple Developer Program 라이선스 계약)를 참조하여 앱이 Apple의 요구사항을 충족하는지 확인하세요.

Apple로 로그인 및 Firebase 인증

Apple 계정으로 인증하려면 우선 사용자가 Apple의 AuthenticationServices 프레임워크를 통해 Apple 계정에 로그인하도록 한 다음 Apple의 응답에서 ID 토큰을 사용하여 Firebase AuthCredential 객체를 만듭니다.

  1. 로그인 요청마다 임의의 문자열인 'nonce'가 생성되며, 이 nonce는 앱의 인증 요청에 대한 응답으로 ID 토큰이 명시적으로 부여되었는지 확인하는 데 사용됩니다. 재전송 공격을 방지하려면 이 단계가 필요합니다.

    다음 예시와 같이 SecRandomCopyBytes(_:_:_)를 사용하여 암호로 보호된 nonce를 생성할 수 있습니다.

    Swift

    private func randomNonceString(length: Int = 32) -> String {
      precondition(length > 0)
      var randomBytes = [UInt8](repeating: 0, count: length)
      let errorCode = SecRandomCopyBytes(kSecRandomDefault, randomBytes.count, &randomBytes)
      if errorCode != errSecSuccess {
        fatalError(
          "Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)"
        )
      }
    
      let charset: [Character] =
        Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._")
    
      let nonce = randomBytes.map { byte in
        // Pick a random character from the set, wrapping around if needed.
        charset[Int(byte) % charset.count]
      }
    
      return String(nonce)
    }
    
        

    Objective-C

    // Adapted from https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-cryptographically-random-nonce
    - (NSString *)randomNonce:(NSInteger)length {
      NSAssert(length > 0, @"Expected nonce to have positive length");
      NSString *characterSet = @"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._";
      NSMutableString *result = [NSMutableString string];
      NSInteger remainingLength = length;
    
      while (remainingLength > 0) {
        NSMutableArray *randoms = [NSMutableArray arrayWithCapacity:16];
        for (NSInteger i = 0; i < 16; i++) {
          uint8_t random = 0;
          int errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random);
          NSAssert(errorCode == errSecSuccess, @"Unable to generate nonce: OSStatus %i", errorCode);
    
          [randoms addObject:@(random)];
        }
    
        for (NSNumber *random in randoms) {
          if (remainingLength == 0) {
            break;
          }
    
          if (random.unsignedIntValue < characterSet.length) {
            unichar character = [characterSet characterAtIndex:random.unsignedIntValue];
            [result appendFormat:@"%C", character];
            remainingLength--;
          }
        }
      }
    
      return [result copy];
    }
        

    로그인 요청과 함께 nonce의 SHA256 해시를 전송하면 Apple은 이에 대한 응답으로 원래의 값을 전달합니다. Firebase는 원래의 nonce를 해싱하고 Apple에서 전달한 값과 비교하여 응답을 검증합니다.

    Swift

    @available(iOS 13, *)
    private func sha256(_ input: String) -> String {
      let inputData = Data(input.utf8)
      let hashedData = SHA256.hash(data: inputData)
      let hashString = hashedData.compactMap {
        String(format: "%02x", $0)
      }.joined()
    
      return hashString
    }
    
        

    Objective-C

    - (NSString *)stringBySha256HashingString:(NSString *)input {
      const char *string = [input UTF8String];
      unsigned char result[CC_SHA256_DIGEST_LENGTH];
      CC_SHA256(string, (CC_LONG)strlen(string), result);
    
      NSMutableString *hashed = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
      for (NSInteger i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
        [hashed appendFormat:@"%02x", result[i]];
      }
      return hashed;
    }
        
  2. Apple의 응답을 처리하는 대리자 클래스와 nonce의 SHA256 해시를 요청에 포함하는 것으로 Apple의 로그인 과정을 시작합니다.

    Swift

    import CryptoKit
    
    // Unhashed nonce.
    fileprivate var currentNonce: String?
    
    @available(iOS 13, *)
    func startSignInWithAppleFlow() {
      let nonce = randomNonceString()
      currentNonce = nonce
      let appleIDProvider = ASAuthorizationAppleIDProvider()
      let request = appleIDProvider.createRequest()
      request.requestedScopes = [.fullName, .email]
      request.nonce = sha256(nonce)
    
      let authorizationController = ASAuthorizationController(authorizationRequests: [request])
      authorizationController.delegate = self
      authorizationController.presentationContextProvider = self
      authorizationController.performRequests()
    }
    

    Objective-C

    @import CommonCrypto;
    
    - (void)startSignInWithAppleFlow {
      NSString *nonce = [self randomNonce:32];
      self.currentNonce = nonce;
      ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
      ASAuthorizationAppleIDRequest *request = [appleIDProvider createRequest];
      request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
      request.nonce = [self stringBySha256HashingString:nonce];
    
      ASAuthorizationController *authorizationController =
          [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
      authorizationController.delegate = self;
      authorizationController.presentationContextProvider = self;
      [authorizationController performRequests];
    }
    
  3. ASAuthorizationControllerDelegate를 구현하여 Apple의 응답을 처리합니다. 로그인에 성공했으면 해시되지 않은 nonce가 포함된 Apple의 응답에서 ID 토큰을 사용하여 Firebase에 인증합니다.

    Swift

    @available(iOS 13.0, *)
    extension MainViewController: ASAuthorizationControllerDelegate {
    
      func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
          guard let nonce = currentNonce else {
            fatalError("Invalid state: A login callback was received, but no login request was sent.")
          }
          guard let appleIDToken = appleIDCredential.identityToken else {
            print("Unable to fetch identity token")
            return
          }
          guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
            print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
            return
          }
          // Initialize a Firebase credential, including the user's full name.
          let credential = OAuthProvider.appleCredential(withIDToken: idTokenString,
                                                            rawNonce: nonce,
                                                            fullName: appleIDCredential.fullName)
          // Sign in with Firebase.
          Auth.auth().signIn(with: credential) { (authResult, error) in
            if error {
              // Error. If error.code == .MissingOrInvalidNonce, make sure
              // you're sending the SHA256-hashed nonce as a hex string with
              // your request to Apple.
              print(error.localizedDescription)
              return
            }
            // User is signed in to Firebase with Apple.
            // ...
          }
        }
      }
    
      func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // Handle error.
        print("Sign in with Apple errored: \(error)")
      }
    
    }
    

    Objective-C

    - (void)authorizationController:(ASAuthorizationController *)controller
       didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {
      if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        ASAuthorizationAppleIDCredential *appleIDCredential = authorization.credential;
        NSString *rawNonce = self.currentNonce;
        NSAssert(rawNonce != nil, @"Invalid state: A login callback was received, but no login request was sent.");
    
        if (appleIDCredential.identityToken == nil) {
          NSLog(@"Unable to fetch identity token.");
          return;
        }
    
        NSString *idToken = [[NSString alloc] initWithData:appleIDCredential.identityToken
                                                  encoding:NSUTF8StringEncoding];
        if (idToken == nil) {
          NSLog(@"Unable to serialize id token from data: %@", appleIDCredential.identityToken);
        }
    
        // Initialize a Firebase credential, including the user's full name.
        FIROAuthCredential *credential = [FIROAuthProvider appleCredentialWithIDToken:IDToken
                                                                             rawNonce:self.appleRawNonce
                                                                             fullName:appleIDCredential.fullName];
    
        // Sign in with Firebase.
        [[FIRAuth auth] signInWithCredential:credential
                                  completion:^(FIRAuthDataResult * _Nullable authResult,
                                               NSError * _Nullable error) {
          if (error != nil) {
            // Error. If error.code == FIRAuthErrorCodeMissingOrInvalidNonce,
            // make sure you're sending the SHA256-hashed nonce as a hex string
            // with your request to Apple.
            return;
          }
          // Sign-in succeeded!
        }];
      }
    }
    
    - (void)authorizationController:(ASAuthorizationController *)controller
               didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
      NSLog(@"Sign in with Apple errored: %@", error);
    }
    

Firebase 인증에서 지원하는 다른 제공업체와 달리, Apple은 사진 URL을 제공하지 않습니다.

또한 사용자가 자신의 이메일을 앱에 공유하지 않으면 Apple은 이 사용자의 고유 이메일 주소(xyz@privaterelay.appleid.com 형식)를 프로비저닝하여 개발자 앱으로 공유합니다. 비공개 이메일 릴레이 서비스를 구성한 경우 Apple은 익명처리된 주소로 전송된 이메일을 사용자의 실제 이메일 주소로 전달합니다.

재인증 및 계정 연결

reauthenticateWithCredential()에도 동일한 패턴을 사용하여, 최근 로그인한 적이 있어야 진행할 수 있는 중요한 작업에서 새로운 사용자 인증 정보를 가져올 수 있습니다.

Swift

// Initialize a fresh Apple credential with Firebase.
let credential = OAuthProvider.credential(
  withProviderID: "apple.com",
  IDToken: appleIdToken,
  rawNonce: rawNonce
)
// Reauthenticate current Apple user with fresh Apple credential.
Auth.auth().currentUser.reauthenticate(with: credential) { (authResult, error) in
  guard error != nil else { return }
  // Apple user successfully re-authenticated.
  // ...
}

Objective-C

FIRAuthCredential *credential = [FIROAuthProvider credentialWithProviderID:@"apple.com",
                                                                   IDToken:appleIdToken,
                                                                  rawNonce:rawNonce];
[[FIRAuth auth].currentUser
    reauthenticateWithCredential:credential
                      completion:^(FIRAuthDataResult * _Nullable authResult,
                                   NSError * _Nullable error) {
  if (error) {
    // Handle error.
  }
  // Apple user successfully re-authenticated.
  // ...
}];

또한 linkWithCredential()을 사용하여 여러 ID 공급업체를 기존 계정에 연결할 수 있습니다.

Apple에서는 개발자가 사용자의 Apple 계정을 다른 데이터에 연결하기 전에 사용자에게 명시적인 동의를 얻도록 요청합니다.

Apple로 로그인을 사용하면 인증 정보를 재사용하여 기존 계정에 연결할 수 없습니다. Apple로 로그인 사용자 인증 정보를 다른 계정에 연결하려면 먼저 이전의 Apple로 로그인 사용자 인증 정보로 계정 연결을 시도한 다음 반환된 오류를 검사하여 새 사용자 인증 정보를 찾아야 합니다. 새 사용자 인증 정보는 오류의 userInfo 사전에 있으며 AuthErrorUserInfoUpdatedCredentialKey 키를 통해 액세스할 수 있습니다.

예를 들어 Facebook 계정을 현재 Firebase 계정에 연결하려면 사용자가 Facebook에 로그인할 때 얻은 액세스 토큰을 사용하세요.

Swift

// Initialize a Facebook credential with Firebase.
let credential = FacebookAuthProvider.credential(
  withAccessToken: AccessToken.current!.tokenString
)
// Assuming the current user is an Apple user linking a Facebook provider.
Auth.auth().currentUser.link(with: credential) { (authResult, error) in
  // Facebook credential is linked to the current Apple user.
  // The user can now sign in with Facebook or Apple to the same Firebase
  // account.
  // ...
}

Objective-C

// Initialize a Facebook credential with Firebase.
FacebookAuthCredential *credential = [FIRFacebookAuthProvider credentialWithAccessToken:accessToken];
// Assuming the current user is an Apple user linking a Facebook provider.
[FIRAuth.auth linkWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
  // Facebook credential is linked to the current Apple user.
  // The user can now sign in with Facebook or Apple to the same Firebase
  // account.
  // ...
}];

토큰 취소

Apple에서는 App Store 검토 가이드라인에 설명된 대로 계정 생성을 지원하는 앱이 사용자가 앱 내에서 계정 삭제를 시작할 수 있도록 해야 허용한다고 요청합니다.

이 요구사항을 충족하려면 다음 단계를 구현하세요.

  1. Apple로 로그인 구성 섹션에 설명된 대로 Apple로 로그인 제공업체 구성의 서비스 IDOAuth 코드 흐름 구성 섹션을 작성합니다.

  2. Apple로 로그인으로 사용자를 생성할 때 Firebase는 사용자 토큰을 저장하지 않으므로 토큰을 취소하고 계정을 삭제하기 전에 사용자에게 다시 로그인하도록 요청해야 합니다.

    Swift

    private func deleteCurrentUser() {
      do {
        let nonce = try CryptoUtils.randomNonceString()
        currentNonce = nonce
        let appleIDProvider = ASAuthorizationAppleIDProvider()
        let request = appleIDProvider.createRequest()
        request.requestedScopes = [.fullName, .email]
        request.nonce = CryptoUtils.sha256(nonce)
    
        let authorizationController = ASAuthorizationController(authorizationRequests: [request])
        authorizationController.delegate = self
        authorizationController.presentationContextProvider = self
        authorizationController.performRequests()
      } catch {
        // In the unlikely case that nonce generation fails, show error view.
        displayError(error)
      }
    }
    
    
  3. ASAuthorizationAppleIDCredential에서 승인 코드를 가져오고 이를 사용하여 Auth.auth().revokeToken(withAuthorizationCode:)를 호출하여 사용자의 토큰을 취소합니다.

    Swift

    func authorizationController(controller: ASAuthorizationController,
                                 didCompleteWithAuthorization authorization: ASAuthorization) {
      guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential
      else {
        print("Unable to retrieve AppleIDCredential")
        return
      }
    
      guard let _ = currentNonce else {
        fatalError("Invalid state: A login callback was received, but no login request was sent.")
      }
    
      guard let appleAuthCode = appleIDCredential.authorizationCode else {
        print("Unable to fetch authorization code")
        return
      }
    
      guard let authCodeString = String(data: appleAuthCode, encoding: .utf8) else {
        print("Unable to serialize auth code string from data: \(appleAuthCode.debugDescription)")
        return
      }
    
      Task {
        do {
          try await Auth.auth().revokeToken(withAuthorizationCode: authCodeString)
          try await user?.delete()
          self.updateUI()
        } catch {
          self.displayError(error)
        }
      }
    }
    
    
  4. 마지막으로 사용자 계정 및 모든 관련 데이터를 삭제합니다.

다음 단계

사용자가 처음으로 로그인하면 신규 사용자 계정이 생성되고 사용자가 로그인할 때 사용한 사용자 인증 정보(사용자 이름과 비밀번호, 전화번호 또는 인증 제공업체 정보)에 연결됩니다. 이 신규 계정은 Firebase 프로젝트의 일부로 저장되며 사용자의 로그인 방법에 관계없이 프로젝트 내 모든 앱에서 사용자를 식별하는 데 사용될 수 있습니다.

  • 앱의 User 객체에서 사용자의 기본 프로필 정보를 가져올 수 있습니다. 사용자 관리를 참조하세요.

  • Firebase 실시간 데이터베이스와 Cloud Storage 보안 규칙auth 변수에서 로그인한 사용자의 고유 사용자 ID를 가져온 후 이 ID를 사용하여 사용자가 액세스할 수 있는 데이터를 관리할 수 있습니다.

인증 제공업체의 사용자 인증 정보를 기존 사용자 계정에 연결하면 사용자가 여러 인증 제공업체를 통해 앱에 로그인할 수 있습니다.

사용자를 로그아웃시키려면 signOut:을 호출합니다.

Swift

let firebaseAuth = Auth.auth()
do {
  try firebaseAuth.signOut()
} catch let signOutError as NSError {
  print("Error signing out: %@", signOutError)
}

Objective-C

NSError *signOutError;
BOOL status = [[FIRAuth auth] signOut:&signOutError];
if (!status) {
  NSLog(@"Error signing out: %@", signOutError);
  return;
}

또한 모든 인증 오류에 대한 오류 처리 코드를 추가할 수도 있습니다. 오류 처리를 참조하세요.