Puoi consentire agli utenti di autenticarsi con Firebase utilizzando i loro account Facebook integrando Facebook Login o Facebook Limited Login nella tua app.
Prima di iniziare
Utilizza Swift Package Manager per installare e gestire le dipendenze di Firebase.
- In Xcode, con il progetto dell'app aperto, vai a File > Add Packages (File > Aggiungi pacchetti).
- Quando richiesto, aggiungi il repository dell'SDK delle piattaforme Apple di Firebase:
- Scegli la Firebase Authentication libreria.
- Aggiungi il flag
-ObjCalla sezione Other Linker Flags (Altri flag del linker) delle impostazioni di compilazione del target. - Al termine, Xcode inizierà automaticamente a risolvere e a scaricare le tue dipendenze in background.
https://github.com/firebase/firebase-ios-sdk.git
A questo punto, esegui alcuni passaggi di configurazione:
- Sul sito Facebook for Developers, recupera l'ID app e un segreto dell'app per la tua app.
- Attiva Facebook Login:
- Nella Firebase console, apri la sezione Authentication (Autenticazione).
- Nella scheda Sign-in method (Metodo di accesso), attiva il metodo di accesso Facebook e specifica l'ID app e il segreto dell'app che hai ottenuto da Facebook.
- Assicurati che l'URI di reindirizzamento OAuth (ad es.
my-app-12345.firebaseapp.com/__/auth/handler) sia elencato come uno degli URI di reindirizzamento OAuth nella pagina delle impostazioni dell'app Facebook sul sito Facebook for Developers nella configurazione Product Settings > Facebook Login.
Implementare Facebook Login
Per utilizzare Facebook Login "classico", segui i passaggi qui descritti. In alternativa, puoi utilizzare Facebook Limited Login, come mostrato nella sezione successiva.
- Integra Facebook Login nella tua app seguendo la
documentazione per sviluppatori. Quando inizializzi l'
FBSDKLoginButtonoggetto, imposta un delegato per ricevere gli eventi di accesso e disconnessione. Ad esempio:Nel delegato, implementaSwift
let loginButton = FBSDKLoginButton() loginButton.delegate = self
Objective-C
FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init]; loginButton.delegate = self;
didCompleteWithResult:error:.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); } }
- Importa il modulo
FirebaseCoreinUIApplicationDelegate, nonché tutti gli altri moduli Firebase utilizzati dal delegato dell'app. Ad esempio, per utilizzare Cloud Firestore e 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; // ...
- Configura un'istanza condivisa nel metodo
application(_:didFinishLaunchingWithOptions:)del delegato dell'app:FirebaseAppSwiftUI
// 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];
- Se utilizzi SwiftUI, devi creare un delegato dell'applicazione e collegarlo
alla struttura
ApptramiteUIApplicationDelegateAdaptoroNSApplicationDelegateAdaptor. Devi anche disattivare lo swizzling del delegato dell'app. Per saperne di più, consulta le istruzioni di SwiftUI.SwiftUI
@main struct YourApp: App { // register app delegate for Firebase setup @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { NavigationView { ContentView() } } } }
- Dopo che un utente ha eseguito l'accesso, nell'implementazione di
didCompleteWithResult:error:, recupera un token di accesso per l' utente che ha eseguito l'accesso e scambialo con una credenziale Firebase:Swift
let credential = FacebookAuthProvider .credential(withAccessToken: AccessToken.current!.tokenString)
Objective-C
FIRAuthCredential *credential = [FIRFacebookAuthProvider credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
Implementare Facebook Limited Login
Per utilizzare Facebook Limited Login anziché Facebook Login "classico", completa i passaggi qui descritti.
- Integra Facebook Limited Login nella tua app seguendo la documentazione per sviluppatori.
- Per ogni richiesta di accesso, genera una stringa casuale univoca, un "nonce", che
utilizzerai per assicurarti che il token ID che ricevi sia stato concesso specificamente in
risposta alla richiesta di autenticazione della tua app. Questo passaggio è importante per
prevenire gli attacchi di replay.
Puoi generare un nonce crittograficamente sicuro con
SecRandomCopyBytes(_:_:_), come nell'esempio seguente:Invierai l'hash SHA-256 del nonce con la richiesta di accesso, che Facebook passerà invariato nella risposta. Firebase convalida la risposta eseguendo l'hashing del nonce originale e confrontandolo con il valore passato da Facebook.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; }
- Quando configuri
FBSDKLoginButton, imposta un delegato per ricevere gli eventi di accesso e disconnessione, imposta la modalità di monitoraggio suFBSDKLoginTrackingLimited, e allega un nonce. Ad esempio:Nel delegato, implementaSwift
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:.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); } }
- Importa il modulo
FirebaseCoreinUIApplicationDelegate, nonché tutti gli altri moduli Firebase utilizzati dal delegato dell'app. Ad esempio, per utilizzare Cloud Firestore e 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; // ...
- Configura un'istanza condivisa nel metodo
application(_:didFinishLaunchingWithOptions:)del delegato dell'app:FirebaseAppSwiftUI
// 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];
- Se utilizzi SwiftUI, devi creare un delegato dell'applicazione e collegarlo
alla struttura
ApptramiteUIApplicationDelegateAdaptoroNSApplicationDelegateAdaptor. Devi anche disattivare lo swizzling del delegato dell'app. Per saperne di più, consulta le istruzioni di SwiftUI.SwiftUI
@main struct YourApp: App { // register app delegate for Firebase setup @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { NavigationView { ContentView() } } } }
- Dopo che un utente ha eseguito l'accesso, nell'implementazione di
didCompleteWithResult:error:, utilizza il token ID della risposta di Facebook con il nonce non sottoposto a hashing per ottenere una credenziale Firebase: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];
Autenticarsi con Firebase
Infine, autenticati con Firebase utilizzando la credenziale Firebase:
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; // ... }];
Passaggi successivi
Dopo che un utente ha eseguito l'accesso per la prima volta, viene creato un nuovo account utente collegato alle credenziali, ovvero al nome utente e alla password, al numero di telefono o alle informazioni del provider di autenticazione con cui l'utente ha eseguito l'accesso. Questo nuovo account viene memorizzato come parte del progetto Firebase e può essere utilizzato per identificare un utente in ogni app del progetto, indipendentemente dalla modalità di accesso.
-
Nelle tue app, puoi ottenere le informazioni di base del profilo dell'utente dall'
Useroggetto. Consulta Gestire gli utenti. Nelle regole di sicurezza di Firebase Realtime Database e Cloud Storage , puoi ottenere l'ID utente univoco dell'utente che ha eseguito l'accesso dalla variabile
auth, e utilizzarlo per controllare i dati a cui un utente può accedere.
Per disconnettere un utente, chiama
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; }
Potresti anche voler aggiungere codice di gestione degli errori per l'intera gamma di errori di autenticazione. Consulta Gestire gli errori.