Puoi consentire ai tuoi 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 .
- Quando richiesto, aggiungi il repository SDK delle piattaforme Firebase Apple:
- Scegli la libreria Firebase Authentication.
- Al termine, Xcode inizierà automaticamente a risolvere e scaricare le tue dipendenze in background.
https://github.com/firebase/firebase-ios-sdk
Quindi, esegui alcuni passaggi di configurazione:
- Sul sito Facebook for Developers , ottieni l' ID app e un segreto app per la tua app.
- Abilita l'accesso a Facebook:
- Nella console Firebase , apri la sezione Auth .
- Nella scheda Metodo di accesso , abilita il metodo di accesso a Facebook e specifica l' ID app e il segreto dell'app che hai ottenuto da Facebook.
- Quindi, assicurati che il tuo URI di reindirizzamento OAuth (ad es.
my-app-12345.firebaseapp.com/__/auth/handler
) sia elencato come uno dei tuoi URI di reindirizzamento OAuth nella pagina delle impostazioni dell'app Facebook sul sito Facebook for Developers nel Prodotto Impostazioni > Configurazione accesso Facebook .
Implementa l'accesso a Facebook
Per utilizzare il login Facebook "classico", completare i seguenti passaggi. In alternativa, puoi utilizzare Facebook Limited Login, come mostrato nella sezione successiva.
- Integra Facebook Login nella tua app seguendo la documentazione dello sviluppatore . Quando si inizializza l'oggetto
FBSDKLoginButton
, impostare un delegato per ricevere gli eventi di accesso e disconnessione. Per esempio:Nel tuo delegato, implementaRapido
let loginButton = FBSDKLoginButton() loginButton.delegate = self
Obiettivo-C
FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init]; loginButton.delegate = self;
didCompleteWithResult:error:
.Rapido
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if let error = error { print(error.localizedDescription) return } // ... }
Obiettivo-C
- (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error { if (error == nil) { // ... } else { NSLog(error.localizedDescription); } }
- Importa il modulo
FirebaseCore
nel tuoUIApplicationDelegate
, così come qualsiasi altro modulo Firebase utilizzato dal delegato dell'app. Ad esempio, per utilizzare Cloud Firestore e l'autenticazione:SwiftUI
import SwiftUI import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
Rapido
import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
Obiettivo-C
@import FirebaseCore; @import FirebaseFirestore; @import FirebaseAuth; // ...
- Configura un'istanza condivisa
FirebaseApp
nel metodoapplication(_:didFinishLaunchingWithOptions:)
del delegato dell'app:SwiftUI
// Use Firebase library to configure APIs FirebaseApp.configure()
Rapido
// Use Firebase library to configure APIs FirebaseApp.configure()
Obiettivo-C
// Use Firebase library to configure APIs [FIRApp configure];
- Se utilizzi SwiftUI, devi creare un delegato dell'applicazione e allegarlo alla struttura
App
tramiteUIApplicationDelegateAdaptor
oNSApplicationDelegateAdaptor
. È inoltre necessario disabilitare lo scorrimento del delegato dell'app. Per ulteriori informazioni, consulta le istruzioni 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 correttamente l'accesso, nella tua implementazione di
didCompleteWithResult:error:
, ottieni un token di accesso per l'utente che ha eseguito l'accesso e scambialo con una credenziale Firebase:Rapido
let credential = FacebookAuthProvider .credential(withAccessToken: AccessToken.current!.tokenString)
Obiettivo-C
FIRAuthCredential *credential = [FIRFacebookAuthProvider credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
Implementa l'accesso limitato a Facebook
Per utilizzare Facebook Limited Login invece del "classico" Facebook Login, completare i seguenti passaggi.
- Integra Facebook Limited Login nella tua app seguendo la documentazione dello sviluppatore .
- Per ogni richiesta di accesso, genera una stringa casuale univoca, un "nonce", che utilizzerai per assicurarti che il token ID che ottieni sia stato concesso specificamente in risposta alla richiesta di autenticazione della tua app. Questo passaggio è importante per prevenire gli attacchi di riproduzione. Puoi generare un nonce crittograficamente sicuro con
SecRandomCopyBytes(_:_:_)
, come nell'esempio seguente:Invierai l'hash SHA-256 del nonce con la tua 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.Rapido
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) }
Obiettivo-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]; }
Rapido
@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 }
Obiettivo-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 imposti
FBSDKLoginButton
, imposta un delegato per ricevere gli eventi di accesso e disconnessione, imposta la modalità di tracciamento suFBSDKLoginTrackingLimited
e allega un nonce. Per esempio:Nel tuo delegato, implementaRapido
func setupLoginButton() { let nonce = randomNonceString() currentNonce = nonce loginButton.delegate = self loginButton.loginTracking = .limited loginButton.nonce = sha256(nonce) }
Obiettivo-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:
.Rapido
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if let error = error { print(error.localizedDescription) return } // ... }
Obiettivo-C
- (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error { if (error == nil) { // ... } else { NSLog(error.localizedDescription); } }
- Importa il modulo
FirebaseCore
nel tuoUIApplicationDelegate
, così come qualsiasi altro modulo Firebase utilizzato dal delegato dell'app. Ad esempio, per utilizzare Cloud Firestore e l'autenticazione:SwiftUI
import SwiftUI import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
Rapido
import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
Obiettivo-C
@import FirebaseCore; @import FirebaseFirestore; @import FirebaseAuth; // ...
- Configura un'istanza condivisa
FirebaseApp
nel metodoapplication(_:didFinishLaunchingWithOptions:)
del delegato dell'app:SwiftUI
// Use Firebase library to configure APIs FirebaseApp.configure()
Rapido
// Use Firebase library to configure APIs FirebaseApp.configure()
Obiettivo-C
// Use Firebase library to configure APIs [FIRApp configure];
- Se utilizzi SwiftUI, devi creare un delegato dell'applicazione e allegarlo alla struttura
App
tramiteUIApplicationDelegateAdaptor
oNSApplicationDelegateAdaptor
. È inoltre necessario disabilitare lo scorrimento del delegato dell'app. Per ulteriori informazioni, consulta le istruzioni 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 correttamente l'accesso, nella tua implementazione di
didCompleteWithResult:error:
, utilizza il token ID dalla risposta di Facebook con il nonce senza hash per ottenere una credenziale Firebase:Rapido
// Initialize a Firebase credential. let idTokenString = AuthenticationToken.current?.tokenString let nonce = currentNonce let credential = OAuthProvider.credential(withProviderID: "facebook.com", idToken: idTokenString!, rawNonce: nonce)
Obiettivo-C
// Initialize a Firebase credential. NSString *idTokenString = FBSDKAuthenticationToken.currentAuthenticationToken.tokenString; NSString *rawNonce = self.currentNonce; FIROAuthCredential *credential = [FIROAuthProvider credentialWithProviderID:@"facebook.com" IDToken:idTokenString rawNonce:rawNonce];
Autenticazione con Firebase
Infine, autenticati con Firebase utilizzando le credenziali Firebase:
Rapido
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 // ... }
Obiettivo-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; // ... }];
Prossimi passi
Dopo che un utente ha effettuato l'accesso per la prima volta, viene creato un nuovo account utente e collegato alle credenziali, ovvero nome utente e password, numero di telefono o informazioni sul provider di autenticazione, con cui l'utente ha effettuato l'accesso. Questo nuovo account viene archiviato come parte del tuo progetto Firebase e può essere utilizzato per identificare un utente in ogni app del tuo progetto, indipendentemente dalla modalità di accesso dell'utente.
Nelle tue app puoi ottenere le informazioni di base sul profilo dell'utente dall'oggetto
User
. Vedere Gestire gli utenti .In Firebase Realtime Database and Cloud Storage Security Rules , puoi ottenere l'ID utente univoco dell'utente che ha eseguito l'accesso dalla variabile
auth
e utilizzarlo per controllare a quali dati può accedere un utente.
Puoi consentire agli utenti di accedere alla tua app utilizzando più provider di autenticazione collegando le credenziali del provider di autenticazione a un account utente esistente.
Per disconnettere un utente, chiama signOut:
.
Rapido
let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print("Error signing out: %@", signOutError) }
Obiettivo-C
NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { NSLog(@"Error signing out: %@", signOutError); return; }
Potresti anche voler aggiungere il codice di gestione degli errori per l'intera gamma di errori di autenticazione. Vedere Gestione degli errori .