Firebase Authentication을 사용하면 임시 익명 계정을 생성 및 사용하여 Firebase에 인증할 수 있습니다. 이 임시 익명 계정을 통해 아직 앱에 가입하지 않은 사용자들도 보안 규칙으로 보호받는 데이터를 사용할 수 있습니다. 익명 사용자가 앱에 가입하기로 결정하면 이 사용자의 로그인 인증 정보를 해당 익명 계정에 연결하여 사용자가 추후 세션에서도 보호받는 데이터를 계속 사용하도록 할 수 있습니다.
시작하기 전에
- 
Swift Package Manager를 사용해 Firebase 종속 항목을 설치하고 관리하세요. - 앱 프로젝트를 연 상태로 Xcode에서 File(파일) > Add Packages(패키지 추가)로 이동합니다.
- 메시지가 표시되면 Firebase Apple 플랫폼 SDK 저장소를 추가합니다.
- Firebase Authentication 라이브러리를 선택합니다.
- 타겟 빌드 설정의 Other Linker Flags(기타 링커 플래그) 섹션에 -ObjC플래그를 추가합니다.
- 완료되면 Xcode가 백그라운드에서 자동으로 종속 항목을 확인하고 다운로드하기 시작합니다.
 https://github.com/firebase/firebase-ios-sdk.git 
- 아직 Firebase 프로젝트에 앱을 연결하지 않았다면 Firebase Console에서 연결합니다.
- 다음과 같이 익명 인증을 사용 설정합니다.
    - Firebase Console에서 인증 섹션을 엽니다.
- 로그인 방법 페이지에서 익명 로그인 방법을 사용 설정합니다.
- 선택사항: 프로젝트를 Firebase Authentication with Identity Platform으로 업그레이드한 경우 자동 정리를 사용 설정할 수 있습니다. 이 설정을 사용하면 30일이 지난 익명 계정은 자동으로 삭제됩니다. 자동 정리가 사용 설정된 프로젝트에서는 익명 인증이 더 이상 사용량 한도 또는 결제 할당량에 포함되지 않습니다. 자동 정리를 참조하세요.
 
Firebase에 익명으로 인증
로그아웃 상태의 사용자가 Firebase에 인증이 필요한 앱 기능을 사용할 때 다음 절차를 밟으면 사용자를 익명으로 로그인시킬 수 있습니다.
- UIApplicationDelegate로- FirebaseCore모듈과 앱 대리자가 사용하는 다른 Firebase 모듈을 가져옵니다. 예를 들어 Cloud Firestore와 Authentication을 사용하려면 다음을 따르세요.- SwiftUI- import SwiftUI import FirebaseCore import FirebaseFirestore import FirebaseAuth // ... - Swift- import FirebaseCore import FirebaseFirestore import FirebaseAuth // ... - Objective-C- @import FirebaseCore; @import FirebaseFirestore; @import FirebaseAuth; // ... 
- 앱 대리자의 application(_:didFinishLaunchingWithOptions:)메서드에서FirebaseApp공유 인스턴스를 구성합니다.SwiftUI// Use Firebase library to configure APIs FirebaseApp.configure() Swift// Use Firebase library to configure APIs FirebaseApp.configure() Objective-C// Use Firebase library to configure APIs [FIRApp configure]; 
- SwiftUI를 사용하는 경우 앱 대리자를 만들고 UIApplicationDelegateAdaptor또는NSApplicationDelegateAdaptor를 통해App구조체에 연결해야 합니다. 앱 대리자 재구성도 중지해야 합니다. 자세한 내용은 SwiftUI 안내를 참조하세요.SwiftUI@main struct YourApp: App { // register app delegate for Firebase setup @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { NavigationView { ContentView() } } } } 
- signInAnonymouslyWithCompletion:메서드를 호출합니다.- Swift- Auth.auth().signInAnonymously { authResult, error in // ... } - Objective-C- [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { // ... }]; 
- signInAnonymouslyWithCompletion:메서드가 오류 없이 실행을 마치면- FIRAuthDataResult객체에서 익명 사용자의 계정 데이터를 가져올 수 있습니다.- Swift- guard let user = authResult?.user else { return } let isAnonymous = user.isAnonymous // true let uid = user.uid - Objective-C- FIRUser *user = authResult.user; BOOL isAnonymous = user.anonymous; // YES NSString *uid = user.uid; 
익명 계정을 영구 계정으로 전환
익명 사용자가 앱에 가입하면 사용자가 가입 전에 하던 작업을 신규 계정에서 이어서 하게 할 수 있습니다. 예를 들면 사용자가 가입 전에 장바구니에 담은 물품이 신규 계정의 장바구니에 나타나도록 할 수 있습니다. 그러려면 다음 절차를 완료하세요.
- 사용자가 가입하면 해당 사용자가 선택한 인증 제공업체의 로그인 과정을 진행하되 FIRAuth.signInWith메서드 호출 전까지만 진행합니다. 예를 들어 사용자의 Google ID 토큰, Facebook 액세스 토큰 또는 이메일 주소와 비밀번호를 가져옵니다.
- 다음과 같이 새로운 인증 제공업체의 - FIRAuthCredential을 가져옵니다.- Google 로그인- Swift- guard let authentication = user?.authentication, let idToken = authentication.idToken else { return } let credential = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: authentication.accessToken) - Objective-C- FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken:result.user.idToken.tokenString accessToken:result.user.accessToken.tokenString]; - Facebook 로그인- Swift- let credential = FacebookAuthProvider .credential(withAccessToken: AccessToken.current!.tokenString) - Objective-C- FIRAuthCredential *credential = [FIRFacebookAuthProvider credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString]; - 이메일-비밀번호 로그인- Swift- let credential = EmailAuthProvider.credential(withEmail: email, password: password) - Objective-C- FIRAuthCredential *credential = [FIREmailAuthProvider credentialWithEmail:email password:password]; 
- 다음과 같이 - FIRAuthCredential객체를 로그인한 사용자의- linkWithCredential:completion:메서드에 전달합니다.- Swift- user.link(with: credential) { authResult, error in // ... } } - Objective-C- [[FIRAuth auth].currentUser linkWithCredential:credential completion:^(FIRAuthDataResult *result, NSError *_Nullable error) { // ... }]; 
linkWithCredential:completion: 호출이 성공하면 사용자의 신규 계정에서 익명 계정의 Firebase 데이터에 액세스할 수 있습니다.
자동 정리
프로젝트를 Firebase Authentication with Identity Platform으로 업그레이드한 경우 Firebase Console에서 자동 정리를 사용 설정할 수 있습니다. 이 기능을 사용 설정하면 Firebase에서 30일이 지난 익명 계정을 자동으로 삭제할 수 있습니다. 자동 정리가 사용 설정된 프로젝트에서는 익명 인증이 사용량 한도 또는 결제 할당량에 포함되지 않습니다.
- 자동 정리를 사용 설정한 후 만든 익명 계정은 생성 후 30일이 지나면 언제든지 자동으로 삭제될 수 있습니다.
- 기존 익명 계정은 자동 정리를 사용 설정한 후 30일이 지나면 자동으로 삭제될 수 있습니다.
- 자동 정리를 사용 중지해도 삭제 예약된 익명 계정은 삭제가 예약된 상태로 유지됩니다.
- 익명 계정을 로그인 방법에 연결하여 '업그레이드'할 경우 계정이 자동으로 삭제되지 않습니다.
이 기능을 사용 설정하기 전에 영향을 받는 사용자 수를 확인하고 프로젝트를 Firebase Authentication with Identity Platform으로 업그레이드한 경우 Cloud Logging에서 is_anon으로 필터링할 수 있습니다.
다음 단계
이제 사용자가 Firebase에 인증할 수 있으므로 Firebase 규칙을 사용하여 Firebase 데이터베이스의 데이터에 대한 액세스를 제어할 수 있습니다.