Bạn có thể cho phép người dùng xác thực bằng Firebase thông qua các trình cung cấp OAuth như Twitter bằng cách tích hợp tính năng Đăng nhập OAuth chung vào ứng dụng của bạn bằng SDK Firebase để thực hiện quy trình đăng nhập toàn diện.
Trước khi bắt đầu
Sử dụng Trình quản lý gói Swift để cài đặt và quản lý các phần phụ thuộc Firebase.
- Trong Xcode, khi dự án ứng dụng đang mở, hãy chuyển đến File > Add Packages (Tệp > Thêm gói).
- Khi được nhắc, hãy thêm kho lưu trữ SDK của các nền tảng Apple Firebase:
- Chọn thư viện Firebase Authentication.
- Thêm cờ
-ObjC
vào phần Other Linker Flags (Cờ trình liên kết khác) trong phần cài đặt bản dựng của mục tiêu. - Khi hoàn tất, Xcode sẽ tự động bắt đầu phân giải và tải các phần phụ thuộc xuống ở chế độ nền.
https://github.com/firebase/firebase-ios-sdk.git
Để người dùng đăng nhập bằng tài khoản Twitter, trước tiên, bạn phải bật Twitter làm nhà cung cấp dịch vụ đăng nhập cho dự án Firebase:
Thêm các nhóm sau vào
Podfile
:pod 'FirebaseAuth'
- Trong bảng điều khiển Firebase, hãy mở phần Auth (Xác thực).
- Trên thẻ Phương thức đăng nhập, hãy bật trình cung cấp Twitter.
- Thêm khoá API và mật khẩu API từ bảng điều khiển dành cho nhà phát triển của nhà cung cấp đó vào cấu hình nhà cung cấp:
- Đăng ký ứng dụng của bạn làm ứng dụng dành cho nhà phát triển trên Twitter và lấy khoá API và mật khẩu API OAuth của ứng dụng.
- Đảm bảo rằng URI chuyển hướng OAuth của Firebase (ví dụ:
my-app-12345.firebaseapp.com/__/auth/handler
) được đặt làm URL gọi lại uỷ quyền trong trang cài đặt của ứng dụng trên cấu hình của ứng dụng Twitter.
- Nhấp vào Lưu.
Xử lý quy trình đăng nhập bằng SDK Firebase
Để xử lý quy trình đăng nhập bằng SDK cho nền tảng Apple của Firebase, hãy làm theo các bước sau:
Thêm giao thức URL tuỳ chỉnh vào dự án Xcode:
- Mở cấu hình dự án: nhấp đúp vào tên dự án trong chế độ xem dạng cây ở bên trái. Chọn ứng dụng của bạn trong mục TARGETS (MỤC TIÊU), sau đó chọn thẻ Info (Thông tin) rồi mở rộng mục URL Types (Loại URL).
- Nhấp vào nút + rồi thêm Mã ứng dụng đã mã hoá làm giao thức URL. Bạn có thể tìm thấy Mã ứng dụng đã mã hoá trên trang Cài đặt chung của bảng điều khiển Firebase, trong phần dành cho ứng dụng iOS. Hãy để trống các trường khác.
Khi hoàn tất, cấu hình của bạn sẽ có dạng như sau (nhưng với các giá trị dành riêng cho ứng dụng):
Tạo một thực thể của OAuthProvider bằng mã nhận dạng trình cung cấp twitter.com.
var provider = OAuthProvider(providerID: "twitter.com")
FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"twitter.com"];
Không bắt buộc: Chỉ định các thông số OAuth tuỳ chỉnh bổ sung mà bạn muốn gửi cùng với yêu cầu OAuth.
provider.customParameters = [ "lang": "fr" ]
[provider setCustomParameters:@{@"lang": @"fr"}];
Để biết các thông số mà Twitter hỗ trợ, hãy xem tài liệu về OAuth của Twitter. Xin lưu ý rằng bạn không thể truyền các tham số bắt buộc của Firebase bằng
setCustomParameters
. Các thông số này là client_id, redirect_uri, response_type, scope và state.Không bắt buộc: Nếu bạn muốn tuỳ chỉnh cách ứng dụng hiển thị
SFSafariViewController
hoặcUIWebView
khi hiển thị reCAPTCHA cho người dùng, hãy tạo một lớp tuỳ chỉnh tuân thủ giao thứcAuthUIDelegate
và truyền lớp đó đếncredentialWithUIDelegate
.Xác thực bằng Firebase bằng đối tượng nhà cung cấp OAuth.
provider.getCredentialWith(nil) { credential, error in if error != nil { // Handle error. } if credential != nil { Auth.auth().signIn(with: credential) { authResult, error in if error != nil { // Handle error. } // User is signed in. // IdP data available in authResult.additionalUserInfo.profile. // Twitter OAuth access token can also be retrieved by: // (authResult.credential as? OAuthCredential)?.accessToken // Twitter OAuth ID token can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.idToken // Twitter OAuth secret can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.secret } } }
[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. // Twitter OAuth access token can also be retrieved by: // authResult.credential.accessToken // Twitter OAuth ID token can be retrieved by calling: // authResult.credential.idToken // Twitter OAuth secret can be retrieved by calling: // authResult.credential.secret }]; } }];
Bằng cách sử dụng mã truy cập OAuth, bạn có thể gọi Twitter API.
Ví dụ: để lấy thông tin hồ sơ cơ bản, bạn có thể gọi API REST, truyền mã truy cập trong tiêu đề
Authorization
:https://api.twitter.com/labs/1/users?usernames=TwitterDev
Mặc dù các ví dụ trên tập trung vào luồng đăng nhập, nhưng bạn cũng có thể liên kết nhà cung cấp Twitter với một người dùng hiện có. Ví dụ: bạn có thể liên kết nhiều nhà cung cấp với cùng một người dùng để cho phép họ đăng nhập bằng bất kỳ nhà cung cấp nào.
Auth().currentUser.link(withCredential: credential) { authResult, error in if error != nil { // Handle error. } // Twitter credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // Twitter OAuth access token can also be retrieved by: // (authResult.credential as? OAuthCredential)?.accessToken // Twitter OAuth ID token can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.idToken // Twitter OAuth secret can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.secret }
[[FIRAuth auth].currentUser linkWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { // Handle error. } // Twitter credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // Twitter OAuth access token is can also be retrieved by: // ((FIROAuthCredential *)authResult.credential).accessToken // Twitter OAuth ID token can be retrieved by calling: // ((FIROAuthCredential *)authResult.credential).idToken // Twitter OAuth secret can be retrieved by calling: // ((FIROAuthCredential *)authResult.credential).secret }];
Bạn có thể sử dụng cùng một mẫu với
reauthenticateWithCredential
để truy xuất thông tin xác thực mới cho các thao tác nhạy cảm yêu cầu đăng nhập gần đây.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 // Twitter OAuth ID token can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.idToken // Twitter OAuth secret can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.secret }
[[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 // Twitter OAuth ID token can be retrieved by calling: // ((FIROAuthCredential *)authResult.credential).idToken // Twitter OAuth secret can be retrieved by calling: // ((FIROAuthCredential *)authResult.credential).secret }];
Xử lý lỗi account-exists-with-different-credential
Nếu bạn đã bật chế độ cài đặt Một tài khoản cho mỗi địa chỉ email trong bảng điều khiển Firebase, thì khi người dùng cố gắng đăng nhập vào một nhà cung cấp (chẳng hạn như Twitter) bằng một email đã tồn tại cho nhà cung cấp của người dùng Firebase khác (chẳng hạn như Google), lỗi FIRAuthErrorCodeAccountExistsWithDifferentCredential
sẽ được gửi cùng với đối tượng FIRAuthCredential
tạm thời (thông tin xác thực Twitter). Để hoàn tất quy trình đăng nhập vào trình cung cấp dự kiến, trước tiên, người dùng phải đăng nhập vào trình cung cấp hiện tại (Google) rồi liên kết với FIRAuthCredential
cũ (thông tin xác thực Twitter). Giao diện sẽ có dạng như minh hoạ dưới đây:
// 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; } }]; } }];
Các bước tiếp theo
Sau khi người dùng đăng nhập lần đầu, một tài khoản người dùng mới sẽ được tạo và liên kết với thông tin xác thực (tức là tên người dùng và mật khẩu, số điện thoại hoặc thông tin về nhà cung cấp dịch vụ xác thực) mà người dùng đã đăng nhập. Tài khoản mới này được lưu trữ trong dự án Firebase và có thể được dùng để xác định người dùng trên mọi ứng dụng trong dự án, bất kể người dùng đăng nhập như thế nào.
-
Trong ứng dụng, bạn có thể lấy thông tin hồ sơ cơ bản của người dùng từ đối tượng
User
. Xem phần Quản lý người dùng. Trong Quy tắc bảo mật Firebase Realtime Database và Cloud Storage, bạn có thể lấy mã nhận dạng người dùng duy nhất của người dùng đã đăng nhập từ biến
auth
và sử dụng mã nhận dạng đó để kiểm soát dữ liệu mà người dùng có thể truy cập.
Bạn có thể cho phép người dùng đăng nhập vào ứng dụng của bạn bằng nhiều trình cung cấp dịch vụ xác thực bằng cách liên kết thông tin xác thực của trình cung cấp dịch vụ xác thực với một tài khoản người dùng hiện có.
Để đăng xuất người dùng, hãy gọi
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; }
Bạn cũng nên thêm mã xử lý lỗi cho toàn bộ lỗi xác thực. Xem phần Xử lý lỗi.