Facebook Login veya Facebook Limited Login'i uygulamanıza entegre ederek kullanıcılarınızın Facebook hesaplarını kullanarak Firebase'de kimlik doğrulamasına izin verebilirsiniz.
Başlamadan önce
Firebase bağımlılarını yükleyip yönetmek için Swift Package Manager'ı kullanın.
- Xcode'da, uygulamanız açıkken File > Add Packages (Dosya > Paket Ekle) seçeneğine gidin.
- İstendiğinde Firebase Apple platformları SDK deposunu ekleyin:
- Firebase Authentication kitaplığını seçin.
-ObjC
işaretini hedefinizin derleme ayarlarının Other Linker Flags (Diğer Bağlayıcı İşaretleri) bölümüne ekleyin.- İşlem tamamlandığında Xcode otomatik olarak arka planda bağımlılarınızı çözümlemeye ve indirmeye başlar.
https://github.com/firebase/firebase-ios-sdk.git
Ardından, bazı yapılandırma adımlarını uygulayın:
- Facebook for Developers sitesinde uygulamanız için Uygulama Kimliği ve Uygulama Gizli Anahtarı'nı alın.
- Facebook ile Giriş'i etkinleştirme:
- Firebase konsolunda Auth (Kimlik Doğrulama) bölümünü açın.
- Oturum açma yöntemi sekmesinde Facebook oturum açma yöntemini etkinleştirin ve Facebook'tan aldığınız Uygulama Kimliği ile Uygulama Gizli Anahtarı'nı belirtin.
- Ardından, OAuth yönlendirme URI'nizin (ör.
my-app-12345.firebaseapp.com/__/auth/handler
) Ürün Ayarları > Facebook ile Giriş yapılandırmasında, Facebook for Developers sitesindeki Facebook uygulamanızın ayarlar sayfasında OAuth yönlendirme URI'lerinizden biri olarak listelendiğinden emin olun.
Facebook ile Giriş'i uygulama
"Klasik" Facebook Girişi'ni kullanmak için aşağıdaki adımları tamamlayın. Alternatif olarak, sonraki bölümde gösterildiği gibi Facebook Sınırlı Giriş'i kullanabilirsiniz.
-
Geliştirici dokümanlarını inceleyerek Facebook ile Giriş'i uygulamanıza entegre edin.
FBSDKLoginButton
nesnesini başlattığınızda oturum açma ve kapatma etkinliklerini alacak bir temsilci ayarlayın. Örneğin:Swift
let loginButton = FBSDKLoginButton() loginButton.delegate = self
Objective-C
FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init]; loginButton.delegate = self;
didCompleteWithResult:error:
uygulayın.Swift
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if let error = error { print(error.localizedDescription) return } // ... }
Objective-C
- (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error { if (error == nil) { // ... } else { NSLog(error.localizedDescription); } }
FirebaseCore
modülünüUIApplicationDelegate
dosyanıza ve uygulama temsilcinizin kullandığı diğer Firebase modüllerine aktarın. Örneğin, Cloud Firestore ve Authentication kullanmak için:SwiftUI
import SwiftUI import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
Swift
import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
Objective-C
@import FirebaseCore; @import FirebaseFirestore; @import FirebaseAuth; // ...
- Uygulama temsilcinizin
application(_:didFinishLaunchingWithOptions:)
yönteminde paylaşılan bir örnekFirebaseApp
yapılandırın: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 kullanıyorsanız bir uygulama temsilcisi oluşturup
App
yapınızaUIApplicationDelegateAdaptor
veyaNSApplicationDelegateAdaptor
aracılığıyla eklemeniz gerekir. Ayrıca uygulama temsilcisi karıştırmayı da devre dışı bırakmanız gerekir. Daha fazla bilgi için SwiftUI talimatlarına bakın.SwiftUI
@main struct YourApp: App { // register app delegate for Firebase setup @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { NavigationView { ContentView() } } } }
- Kullanıcı başarılı bir şekilde oturum açtıktan sonra
didCompleteWithResult:error:
uygulamanızda oturum açan kullanıcı için erişim jetonu alın ve bunu Firebase kimlik bilgisiyle değiştirin:Swift
let credential = FacebookAuthProvider .credential(withAccessToken: AccessToken.current!.tokenString)
Objective-C
FIRAuthCredential *credential = [FIRFacebookAuthProvider credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
Facebook Sınırlı Giriş'i uygulama
"Klasik" Facebook Girişi yerine Facebook Limited Login'i kullanmak için aşağıdaki adımları tamamlayın.
- Geliştirici dokümanlarını inceleyerek Facebook Limited Login'i uygulamanıza entegre edin.
- Her oturum açma isteği için benzersiz bir rastgele dize ("nonce") oluşturun. Bu dizeyi, aldığınız kimlik jetonunun özellikle uygulamanızın kimlik doğrulama isteğine yanıt olarak verildiğinden emin olmak için kullanırsınız. Bu adım, yeniden oynatma saldırılarını önlemek için önemlidir.
Aşağıdaki örnekte olduğu gibi,
SecRandomCopyBytes(_:_:_)
ile kriptografik olarak güvenli bir nonce oluşturabilirsiniz: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]; }
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; }
FBSDKLoginButton
özelliğini ayarlarken oturum açma ve kapatma etkinliklerini alacak bir temsilci belirleyin, izleme modunuFBSDKLoginTrackingLimited
olarak ayarlayın ve bir nonce ekleyin. Örneğin:Swift
func setupLoginButton() { let nonce = randomNonceString() currentNonce = nonce loginButton.delegate = self loginButton.loginTracking = .limited loginButton.nonce = sha256(nonce) }
Objective-C
- (void)setupLoginButton { NSString *nonce = [self randomNonce:32]; self.currentNonce = nonce; self.loginButton.delegate = self; self.loginButton.loginTracking = FBSDKLoginTrackingLimited self.loginButton.nonce = [self stringBySha256HashingString:nonce]; }
didCompleteWithResult:error:
uygulayın.Swift
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if let error = error { print(error.localizedDescription) return } // ... }
Objective-C
- (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error { if (error == nil) { // ... } else { NSLog(error.localizedDescription); } }
FirebaseCore
modülünüUIApplicationDelegate
dosyanıza ve uygulama temsilcinizin kullandığı diğer Firebase modüllerine aktarın. Örneğin, Cloud Firestore ve Authentication kullanmak için:SwiftUI
import SwiftUI import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
Swift
import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
Objective-C
@import FirebaseCore; @import FirebaseFirestore; @import FirebaseAuth; // ...
- Uygulama temsilcinizin
application(_:didFinishLaunchingWithOptions:)
yönteminde paylaşılan bir örnekFirebaseApp
yapılandırın: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 kullanıyorsanız bir uygulama temsilcisi oluşturup
App
yapınızaUIApplicationDelegateAdaptor
veyaNSApplicationDelegateAdaptor
aracılığıyla eklemeniz gerekir. Ayrıca uygulama temsilcisi karıştırmayı da devre dışı bırakmanız gerekir. Daha fazla bilgi için SwiftUI talimatlarına bakın.SwiftUI
@main struct YourApp: App { // register app delegate for Firebase setup @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { NavigationView { ContentView() } } } }
- Bir kullanıcı başarıyla oturum açtıktan sonra,
didCompleteWithResult:error:
uygulamanızda, Firebase kimlik bilgisi almak için Facebook'un yanıtındaki kimlik jetonunu karma oluşturulmamış tek seferlik sayı ile birlikte kullanın:Swift
// Initialize a Firebase credential. let idTokenString = AuthenticationToken.current?.tokenString let nonce = currentNonce let credential = OAuthProvider.credential(withProviderID: "facebook.com", idToken: idTokenString!, rawNonce: nonce)
Objective-C
// Initialize a Firebase credential. NSString *idTokenString = FBSDKAuthenticationToken.currentAuthenticationToken.tokenString; NSString *rawNonce = self.currentNonce; FIROAuthCredential *credential = [FIROAuthProvider credentialWithProviderID:@"facebook.com" IDToken:idTokenString rawNonce:rawNonce];
Firebase ile kimlik doğrulama
Son olarak, Firebase kimlik bilgisini kullanarak Firebase ile kimlik doğrulayın:
Swift
Auth.auth().signIn(with: credential) { authResult, error in if let error = error { let authError = error as NSError if isMFAEnabled, authError.code == AuthErrorCode.secondFactorRequired.rawValue { // The user is a multi-factor user. Second factor challenge is required. let resolver = authError .userInfo[AuthErrorUserInfoMultiFactorResolverKey] as! MultiFactorResolver var displayNameString = "" for tmpFactorInfo in resolver.hints { displayNameString += tmpFactorInfo.displayName ?? "" displayNameString += " " } self.showTextInputPrompt( withMessage: "Select factor to sign in\n\(displayNameString)", completionBlock: { userPressedOK, displayName in var selectedHint: PhoneMultiFactorInfo? for tmpFactorInfo in resolver.hints { if displayName == tmpFactorInfo.displayName { selectedHint = tmpFactorInfo as? PhoneMultiFactorInfo } } PhoneAuthProvider.provider() .verifyPhoneNumber(with: selectedHint!, uiDelegate: nil, multiFactorSession: resolver .session) { verificationID, error in if error != nil { print( "Multi factor start sign in failed. Error: \(error.debugDescription)" ) } else { self.showTextInputPrompt( withMessage: "Verification code for \(selectedHint?.displayName ?? "")", completionBlock: { userPressedOK, verificationCode in let credential: PhoneAuthCredential? = PhoneAuthProvider.provider() .credential(withVerificationID: verificationID!, verificationCode: verificationCode!) let assertion: MultiFactorAssertion? = PhoneMultiFactorGenerator .assertion(with: credential!) resolver.resolveSignIn(with: assertion!) { authResult, error in if error != nil { print( "Multi factor finanlize sign in failed. Error: \(error.debugDescription)" ) } else { self.navigationController?.popViewController(animated: true) } } } ) } } } ) } else { self.showMessagePrompt(error.localizedDescription) return } // ... return } // User is signed in // ... }
Objective-C
[[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (isMFAEnabled && error && error.code == FIRAuthErrorCodeSecondFactorRequired) { FIRMultiFactorResolver *resolver = error.userInfo[FIRAuthErrorUserInfoMultiFactorResolverKey]; NSMutableString *displayNameString = [NSMutableString string]; for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) { [displayNameString appendString:tmpFactorInfo.displayName]; [displayNameString appendString:@" "]; } [self showTextInputPromptWithMessage:[NSString stringWithFormat:@"Select factor to sign in\n%@", displayNameString] completionBlock:^(BOOL userPressedOK, NSString *_Nullable displayName) { FIRPhoneMultiFactorInfo* selectedHint; for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) { if ([displayName isEqualToString:tmpFactorInfo.displayName]) { selectedHint = (FIRPhoneMultiFactorInfo *)tmpFactorInfo; } } [FIRPhoneAuthProvider.provider verifyPhoneNumberWithMultiFactorInfo:selectedHint UIDelegate:nil multiFactorSession:resolver.session completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) { if (error) { [self showMessagePrompt:error.localizedDescription]; } else { [self showTextInputPromptWithMessage:[NSString stringWithFormat:@"Verification code for %@", selectedHint.displayName] completionBlock:^(BOOL userPressedOK, NSString *_Nullable verificationCode) { FIRPhoneAuthCredential *credential = [[FIRPhoneAuthProvider provider] credentialWithVerificationID:verificationID verificationCode:verificationCode]; FIRMultiFactorAssertion *assertion = [FIRPhoneMultiFactorGenerator assertionWithCredential:credential]; [resolver resolveSignInWithAssertion:assertion completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { [self showMessagePrompt:error.localizedDescription]; } else { NSLog(@"Multi factor finanlize sign in succeeded."); } }]; }]; } }]; }]; } else if (error) { // ... return; } // User successfully signed in. Get user data from the FIRUser object if (authResult == nil) { return; } FIRUser *user = authResult.user; // ... }];
Sonraki adımlar
Bir kullanıcı ilk kez oturum açtıktan sonra yeni bir kullanıcı hesabı oluşturulur ve kullanıcının oturum açtığı kimlik bilgilerine (kullanıcı adı ve şifre, telefon numarası veya kimlik doğrulama sağlayıcı bilgileri) bağlanır. Bu yeni hesap, Firebase projenizin bir parçası olarak depolanır ve kullanıcının nasıl oturum açtığına bakılmaksızın projenizdeki her uygulamada kullanıcıyı tanımlamak için kullanılabilir.
-
Uygulamalarınızda, kullanıcının temel profil bilgilerini
User
nesnesinden alabilirsiniz. Kullanıcıları yönetme başlıklı makaleyi inceleyin. Firebase Realtime Database ve Cloud Storage Güvenlik Kurallarınızda, oturum açmış kullanıcının benzersiz kullanıcı kimliğini
auth
değişkeninden alabilir ve kullanıcının hangi verilere erişebileceğini kontrol etmek için bu kimliği kullanabilirsiniz.
Kimlik doğrulama sağlayıcı kimlik bilgilerini mevcut bir kullanıcı hesabına bağlayarak kullanıcıların uygulamanızda birden fazla kimlik doğrulama sağlayıcı kullanarak oturum açmasına izin verebilirsiniz.
Bir kullanıcının oturumunu kapatmak için
signOut:
işlevini çağırın.
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; }
Ayrıca, kimlik doğrulama hatalarının tamamı için hata işleme kodu eklemek de isteyebilirsiniz. Hataları İşleme bölümüne bakın.