Możesz zezwolić użytkownikom na uwierzytelnianie w Firebase za pomocą dostawców protokołu OAuth, takich jak GitHub, integrując ogólne logowanie OAuth z aplikacją za pomocą pakietu SDK Firebase, i cały proces logowania.
Zanim zaczniesz
Aby zalogować użytkowników przy użyciu kont GitHub, musisz najpierw włączyć logowanie się w GitHubie dla swojego projektu Firebase:
Użyj menedżera pakietów Swift, aby zainstalować zależności Firebase i nimi zarządzać.
- W Xcode po otwarciu projektu aplikacji przejdź do File > Dodaj pakiety.
- Gdy pojawi się prośba, dodaj repozytorium SDK platform Apple Platform SDK Firebase:
- Wybierz bibliotekę Firebase Authentication.
- Dodaj flagę
-ObjC
do sekcji Inne flagi łączące w ustawieniach kompilacji celu. - Po zakończeniu Xcode automatycznie rozpocznie rozpoznawanie i pobieranie lub zależności w tle.
https://github.com/firebase/firebase-ios-sdk.git
Teraz wykonaj kilka czynności konfiguracyjnych:
- W konsoli Firebase otwórz sekcję Uwierzytelnianie.
- Na karcie Metoda logowania włącz dostawcę GitHub.
- Dodaj Client ID (Identyfikator klienta) i Client Secret (Tajny klucz klienta) z konsoli programisty tego dostawcy do
konfiguracja dostawcy:
- Rejestrowanie aplikacji jako programistę w GitHubie i uzyskaj identyfikator klienta OAuth 2.0 swojej aplikacji. i Client Secret (Tajny klucz klienta).
- Sprawdź, czy identyfikator URI przekierowania OAuth Firebase (np.
my-app-12345.firebaseapp.com/__/auth/handler
) jest ustawiony jako URL wywołania zwrotnego autoryzacji na stronie ustawień aplikacji Konfiguracja aplikacji GitHub.
- Kliknij Zapisz.
Zarejestruj się za pomocą pakietu SDK Firebase
Aby zalogować się za pomocą pakietu SDK platform Firebase Apple, wykonaj te czynności:
Dodaj niestandardowe schematy adresów URL do projektu Xcode:
- Otwórz konfigurację projektu: kliknij dwukrotnie jego nazwę w lewy widok drzewa. Wybierz aplikację w sekcji CELE, a potem wybierz kartę Informacje i rozwiń sekcję Typy adresów URL.
- Kliknij przycisk + i dodaj zakodowany identyfikator aplikacji jako adres URL.
oszustw. Zakodowany identyfikator aplikacji znajdziesz w
Ogólne
Ustawienia w konsoli Firebase w sekcji dotyczącej iOS.
. Pozostałe pola pozostaw puste.
Po zakończeniu konfiguracja powinna wyglądać podobnie do następujące (ale z wartościami związanymi z daną aplikacją):
Utwórz instancję OAuthProvider za pomocą identyfikatora dostawcy. github.com
var provider = OAuthProvider(providerID: "github.com")
FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"github.com"];
Opcjonalnie: określ dodatkowe niestandardowe parametry OAuth, które chcesz stosować wysyłać z żądaniem OAuth.
provider.customParameters = [ "allow_signup": "false" ]
[provider setCustomParameters:@{@"allow_signup": @"false"}];
Parametry obsługiwane przez GitHub znajdziesz w Dokumentacja protokołu OAuth na GitHubie. Pamiętaj, że parametrów wymaganych przez Firebase nie można przekazywać za pomocą funkcji
setCustomParameters
Te parametry to client_id, redirect_uri, response_type, scope i state.Opcjonalnie: określ dodatkowe zakresy OAuth 2.0 poza podstawowym profilem, które których chcesz żądać od dostawcy uwierzytelniania. Jeśli Twoja aplikacja wymaga dostępu do prywatnych danych użytkownika z interfejsów GitHub API, musisz wykonać poproś o uprawnienia dostępu do interfejsów GitHub API w sekcji API Permissions (Uprawnienia interfejsu API) w Konsola programisty GitHub. Żądane zakresy protokołu OAuth muszą dokładnie pasować do skonfigurowane wstępnie w uprawnieniach dotyczących interfejsu API aplikacji.
// Request read access to a user's email addresses. // This must be preconfigured in the app's API permissions. provider.scopes = ["user:email"]
// Request read access to a user's email addresses. // This must be preconfigured in the app's API permissions. [provider setScopes:@[@"user:email"]];
Aby dowiedzieć się więcej, zapoznaj się z Dokumentacja zakresów na GitHubie.
Opcjonalnie: jeśli chcesz dostosować sposób, w jaki aplikacja prezentuje
SFSafariViewController
lubUIWebView
, gdy wyświetlając reCAPTCHA użytkownikowi, utwórz niestandardową klasę spełniającą wymagania do protokołuAuthUIDelegate
i przekazać go docredentialWithUIDelegate
.Uwierzytelniaj w Firebase za pomocą obiektu dostawcy OAuth.
provider.getCredentialWith(nil) { credential, error in if error != nil { // Handle error. } if credential != nil { Auth().signIn(with: credential) { authResult, error in if error != nil { // Handle error. } // User is signed in. // IdP data available in authResult.additionalUserInfo.profile. guard let oauthCredential = authResult.credential as? OAuthCredential else { return } // GitHub OAuth access token can also be retrieved by: // oauthCredential.accessToken // GitHub OAuth ID token can be retrieved by calling: // oauthCredential.idToken } } }
[provider getCredentialWithUIDelegate:nil completion:^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) { if (error) { // Handle error. } if (credential) { [[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) { if (error) { // Handle error. } // User is signed in. // IdP data available in authResult.additionalUserInfo.profile. FIROAuthCredential *oauthCredential = (FIROAuthCredential *)authResult.credential; // GitHub OAuth access token can also be retrieved by: // oauthCredential.accessToken // GitHub OAuth ID token can be retrieved by calling: // oauthCredential.idToken }]; } }];
Korzystając z tokena dostępu OAuth, możesz wywoływać metodę Interfejs API GitHub.
Aby na przykład uzyskać podstawowe informacje o profilu, możesz wywołać interfejs API REST, przekazując token dostępu w nagłówku
Authorization
:https://api.github.com/user
Powyższe przykłady dotyczą procesu logowania, ale masz też możliwość połączenia dostawcy GitHuba z istniejącym użytkownikiem. Możesz na przykład: Połączyć wielu dostawców z tym samym użytkownikiem, umożliwiając im logowanie się za pomocą dowolnej z tych usług.
Auth().currentUser.link(withCredential: credential) { authResult, error in if error != nil { // Handle error. } // GitHub credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // GitHub OAuth access token can also be retrieved by: // (authResult.credential as? OAuthCredential)?.accessToken // GitHub OAuth ID token can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.idToken }
[[FIRAuth auth].currentUser linkWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { // Handle error. } // GitHub credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // GitHub OAuth access token is can also be retrieved by: // ((FIROAuthCredential *)authResult.credential).accessToken // GitHub OAuth ID token can be retrieved by calling: // ((FIROAuthCredential *)authResult.credential).idToken }];
Tego samego wzorca można użyć z funkcją
reauthenticateWithCredential
, która może służy do pobierania nowych danych logowania na potrzeby operacji poufnych, które wymagają ostatniego logowania.Auth().currentUser.reauthenticateWithCredential(withCredential: credential) { authResult, error in if error != nil { // Handle error. } // User is re-authenticated with fresh tokens minted and // should be able to perform sensitive operations like account // deletion and email or password update. // IdP data available in result.additionalUserInfo.profile. // Additional OAuth access token is can also be retrieved by: // (authResult.credential as? OAuthCredential)?.accessToken // GitHub OAuth ID token can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.idToken }
[[FIRAuth auth].currentUser reauthenticateWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { // Handle error. } // User is re-authenticated with fresh tokens minted and // should be able to perform sensitive operations like account // deletion and email or password update. // IdP data available in result.additionalUserInfo.profile. // Additional OAuth access token is can also be retrieved by: // ((FIROAuthCredential *)authResult.credential).accessToken // GitHub OAuth ID token can be retrieved by calling: // ((FIROAuthCredential *)authResult.credential).idToken }];
Postępowanie w przypadku błędów dotyczących konta z innymi danymi logowania
Jeśli w konsoli Firebase masz włączone ustawienie Jedno konto na każdy adres e-mail,
gdy użytkownik próbuje zalogować się na stronie dostawcy (np. GitHuba) przy użyciu adresu e-mail, który
dla dostawcy innego użytkownika Firebase (np. Google), błąd
Rzucany FIRAuthErrorCodeAccountExistsWithDifferentCredential
wraz z tymczasowym strzałem
Obiekt FIRAuthCredential
(dane logowania do GitHuba). Aby dokończyć logowanie się w
do dostawcy usług, użytkownik musi najpierw zalogować się do istniejącego dostawcy (Google), a następnie dodać link
poprzednie dane logowania w serwisie FIRAuthCredential
(dane logowania GitHub). Wygląda to w taki sposób, jak pokazano poniżej:
// Sign-in with an OAuth credential. provider.getCredentialWith(nil) { credential, error in // An account with the same email already exists. if (error as NSError?)?.code == AuthErrorCode.accountExistsWithDifferentCredential.rawValue { // Get pending credential and email of existing account. let existingAcctEmail = (error! as NSError).userInfo[AuthErrorUserInfoEmailKey] as! String let pendingCred = (error! as NSError).userInfo[AuthErrorUserInfoUpdatedCredentialKey] as! AuthCredential // Lookup existing account identifier by the email. Auth.auth().fetchProviders(forEmail:existingAcctEmail) { providers, error in // Existing email/password account. if (providers?.contains(EmailAuthProviderID))! { // Existing password account for email. Ask user to provide the password of the // existing account. // Sign in with existing account. Auth.auth().signIn(withEmail:existingAcctEmail, password:password) { user, error in // Successfully signed in. if user != nil { // Link pending credential to account. Auth.auth().currentUser?.linkAndRetrieveData(with: pendingCred) { result, error in // ... } } } } } return } // Other errors. if error != nil { // handle the error. return } // Sign in with the credential. if credential != nil { Auth.auth().signInAndRetrieveData(with: credential!) { result, error in if error != nil { // handle the error. return } } } }
// Sign-in with an OAuth credential. [provider getCredentialWithUIDelegate:nil completion:^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) { // An account with the same email already exists. if (error.code == FIRAuthErrorCodeAccountExistsWithDifferentCredential) { // Get pending credential and email of existing account. NSString *existingAcctEmail = error.userInfo[FIRAuthErrorUserInfoEmailKey]; FIRAuthCredential *pendingCred = error.userInfo[FIRAuthErrorUserInfoUpdatedCredentialKey]; // Lookup existing account identifier by the email. [[FIRAuth auth] fetchProvidersForEmail:existingAcctEmail completion:^(NSArray<NSString *> *_Nullable providers, NSError *_Nullable error) { // Existing email/password account. if ( [providers containsObject:FIREmailAuthProviderID] ) { // Existing password account for email. Ask user to provide the password of the // existing account. // Sign in with existing account. [[FIRAuth auth] signInWithEmail:existingAcctEmail password:password completion:^(FIRUser *user, NSError *error) { // Successfully signed in. if (user) { // Link pending credential to account. [[FIRAuth auth].currentUser linkWithCredential:pendingCred completion:^(FIRUser *_Nullable user, NSError *_Nullable error) { // ... }]; } }]; } }]; return; } // Other errors. if (error) { // handle the error. return; } // Sign in with the credential. if (credential) { [[FIRAuth auth] signInAndRetrieveDataWithCredential:credential completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) { if (error) { // handle the error. return; } }]; } }];
Dalsze kroki
Gdy użytkownik zaloguje się po raz pierwszy, tworzone jest nowe konto użytkownika. powiązane z danymi logowania, czyli z nazwą użytkownika, hasłem i numerem telefonu, numer telefonu lub informacje o dostawcy uwierzytelniania – użytkownik zalogowany. Ten nowy jest przechowywane w ramach projektu Firebase i może służyć do identyfikowania użytkownika w każdej aplikacji w projekcie, niezależnie od tego, jak się loguje.
-
W swoich aplikacjach możesz uzyskać podstawowe informacje o profilu użytkownika z
User
. Zobacz Zarządzanie użytkownikami. Na liście Firebase Realtime Database i Cloud Storage regułami zabezpieczeń, pobierz ze zmiennej
auth
unikalny identyfikator zalogowanego użytkownika, i używać ich do kontrolowania, do jakich danych użytkownik ma dostęp.
Możesz zezwolić użytkownikom na logowanie się w aplikacji przy użyciu wielokrotnego uwierzytelniania. dostawców, łącząc dane logowania dostawcy uwierzytelniania z istniejącego konta użytkownika.
Aby wylogować użytkownika, wywołaj
signOut:
let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print("Error signing out: %@", signOutError) }
NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { NSLog(@"Error signing out: %@", signOutError); return; }
Można także dodać kod obsługi błędów dla pełnego zakresu uwierzytelniania . Patrz Obsługa błędów.