Bạn có thể cho phép người dùng của bạn xác thực với căn cứ hỏa lực sử dụng tài khoản Google của họ bằng cách tích hợp Google đăng nhập vào ứng dụng của bạn.
Trước khi bắt đầu
- Thêm căn cứ hỏa lực cho dự án Apple của bạn . Bao gồm vỏ sau trong bạn
Podfile
:pod 'FirebaseAuth' pod 'GoogleSignIn'
- Nếu bạn chưa kết nối với ứng dụng của bạn để dự án căn cứ hỏa lực của bạn, làm như vậy từ các căn cứ hỏa lực console .
- Kích hoạt tính năng Google như thông tin đăng nhập phương pháp trong các căn cứ hỏa lực console:
- Trong căn cứ hỏa lực console , hãy mở phần Auth.
- Trên Đăng nhập tab phương pháp, cho phép đăng nhập Google phương pháp và nhấn Save.
1. Nhập khẩu các tập tin tiêu đề cần thiết
Đầu tiên, bạn phải nhập các tập tin tiêu đề căn cứ hỏa lực SDK và Google Đăng trong SDK vào ứng dụng của bạn.
Nhanh
import FirebaseCore import GoogleSignIn
Objective-C
@import FirebaseCore; @import GoogleSignIn;
2. Thực hiện đăng nhập vào Google
Thực hiện đăng nhập vào Google bằng cách làm theo các bước sau. Xem Google Đăng trong tài liệu hướng dẫn phát triển để biết chi tiết về việc sử dụng Google Sign-In với iOS.
- Thêm chương trình URL tùy chỉnh cho dự án Xcode của bạn:
- Mở cấu hình dự án của bạn: kích đúp vào tên dự án trong màn hình cây trái. Chọn ứng dụng của bạn từ phần MỤC TIÊU, sau đó chọn tab Info, và mở rộng phần loại URL.
- Nhấp vào nút +, và thêm một thức truy cập URL cho ID khách hàng đảo ngược của bạn. Để tìm giá trị này, mở
tập tin cấu hình, và nhìn choGoogleService-Info.plist REVERSED_CLIENT_ID
then chốt. Sao chép giá trị của key đó, và dán nó vào URL Schemes hộp tìm kiếm trên trang cấu hình. Rời khỏi lĩnh vực trống khác.Khi hoàn thành, cấu hình của bạn sẽ giống tương tự như sau (nhưng với các giá trị riêng cho ứng dụng):
- Trong đại biểu ứng dụng của bạn
application:didFinishLaunchingWithOptions:
phương pháp, cấu hìnhFirebaseApp
đối tượng.Nhanh
// Use Firebase library to configure APIs FirebaseApp.configure()
Objective-C
// Use Firebase library to configure APIs [FIRApp configure];
- Thực hiện các
application:openURL:options:
phương pháp đại biểu ứng dụng của bạn. Phương pháp này nên gọihandleURL
phương pháp củaGIDSignIn
dụ, mà sẽ xử lý đúng đắn các URL mà ứng dụng của bạn nhận được vào cuối của quá trình xác thực.Nhanh
@available(iOS 9.0, *) func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool { return GIDSignIn.sharedInstance.handle(url) }
Objective-C
- (BOOL)application:(nonnull UIApplication *)application openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<NSString *, id> *)options { return [[GIDSignIn sharedInstance] handleURL:url]; }
- Vượt qua điều khiển xem trình bày và ID khách hàng cho ứng dụng của bạn với Google Đăng nhập đăng nhập phương pháp và tạo ra một căn cứ hỏa lực auth chứng từ kết quả của Google auth mã thông báo:
Nhanh
guard let clientID = FirebaseApp.app()?.options.clientID else { return } // Create Google Sign In configuration object. let config = GIDConfiguration(clientID: clientID) // Start the sign in flow! GIDSignIn.sharedInstance.signIn(with: config, presenting: self) { [unowned self] user, error in if let error = error { // ... return } guard let authentication = user?.authentication, let idToken = authentication.idToken else { return } let credential = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: authentication.accessToken) // ... }
Objective-C
GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:[FIRApp defaultApp].options.clientID]; __weak __auto_type weakSelf = self; [GIDSignIn.sharedInstance signInWithConfiguration:config presentingViewController:self callback:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) { __auto_type strongSelf = weakSelf; if (strongSelf == nil) { return; } if (error == nil) { GIDAuthentication *authentication = user.authentication; FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken accessToken:authentication.accessToken]; // ... } else { // ... } }];
- Thêm một
GIDSignInButton
vào bảng phân cảnh của bạn, tập tin XIB, hoặc nhanh chóng nó lập trình. Để thêm nút vào bảng phân cảnh của bạn hoặc tập tin XIB, thêm một Xem và thiết lập lớp tùy chỉnh nó đểGIDSignInButton
. - Tùy chọn: Nếu bạn muốn tùy chỉnh các nút, làm như sau:
Nhanh
- Trong điều khiển xem của bạn, kê khai đăng nhập nút như một tài sản.
@IBOutlet weak var signInButton: GIDSignInButton!
- Kết nối vào nút để các
signInButton
tài sản mà bạn vừa khai báo. - Tùy chỉnh các nút bằng cách thiết lập các thuộc tính của GIDSignInButton đối tượng.
Objective-C
- Trong phần đầu tập tin điều khiển quan điểm của bạn, kê khai đăng nhập nút như một tài sản.
@property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
- Kết nối vào nút để các
signInButton
tài sản mà bạn vừa khai báo. - Tùy chỉnh các nút bằng cách thiết lập các thuộc tính của GIDSignInButton đối tượng.
- Trong điều khiển xem của bạn, kê khai đăng nhập nút như một tài sản.
3. Authenticate với căn cứ hỏa lực
Cuối cùng, hoàn tất quá trình đăng nhập căn cứ hỏa lực với chứng chỉ auth tạo ra trong bước trước.
Nhanh
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; // ... }];
Bước tiếp theo
Sau một người dùng đăng nhập lần đầu tiên, một tài khoản người dùng mới được tạo ra và liên quan đến các chứng chỉ-có nghĩa là, tên người dùng và mật khẩu, số điện thoại, hoặc auth cung cấp thông tin người dùng đăng nhập bằng. Tài khoản mới này được lưu giữ như một phần của dự án căn cứ hỏa lực của bạn, và có thể được sử dụng để xác định một người dùng trên mọi ứng dụng trong dự án của bạn, bất kể như thế nào người dùng đăng nhập.
Trong các ứng dụng của bạn, bạn có thể nhận được thông tin hồ sơ cơ bản của người dùng từ các
FIRUser
đối tượng. Xem Quản lý người dùng .Trong Cơ sở dữ liệu căn cứ hỏa lực Realtime của bạn và lưu trữ đám mây Security Rules , bạn có thể nhận được đã đăng nhập của người sử dụng ID người dùng duy nhất từ
auth
biến, và sử dụng nó để kiểm soát dữ liệu 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 sử dụng nhiều nhà cung cấp chứng thực bởi liên kết auth thông tin cung cấp cho một tài khoản người dùng hiện có.
Đăng xuất khỏi một người sử dụng, hãy gọi signOut:
.
Nhanh
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; }
Bạn cũng có thể muốn thêm mã xử lý lỗi cho phạm vi đầy đủ các lỗi xác thực. Xem lỗi Xử lý .
,Bạn có thể cho phép người dùng của bạn xác thực với căn cứ hỏa lực sử dụng tài khoản Google của họ bằng cách tích hợp Google đăng nhập vào ứng dụng của bạn.
Trước khi bắt đầu
- Thêm căn cứ hỏa lực cho dự án Apple của bạn . Bao gồm vỏ sau trong bạn
Podfile
:pod 'FirebaseAuth' pod 'GoogleSignIn'
- Nếu bạn chưa kết nối với ứng dụng của bạn để dự án căn cứ hỏa lực của bạn, làm như vậy từ các căn cứ hỏa lực console .
- Kích hoạt tính năng Google như thông tin đăng nhập phương pháp trong các căn cứ hỏa lực console:
- Trong căn cứ hỏa lực console , hãy mở phần Auth.
- Trên Đăng nhập tab phương pháp, cho phép đăng nhập Google phương pháp và nhấn Save.
1. Nhập khẩu các tập tin tiêu đề cần thiết
Đầu tiên, bạn phải nhập các tập tin tiêu đề căn cứ hỏa lực SDK và Google Đăng trong SDK vào ứng dụng của bạn.
Nhanh
import FirebaseCore import GoogleSignIn
Objective-C
@import FirebaseCore; @import GoogleSignIn;
2. Thực hiện đăng nhập vào Google
Thực hiện đăng nhập vào Google bằng cách làm theo các bước sau. Xem Google Đăng trong tài liệu hướng dẫn phát triển để biết chi tiết về việc sử dụng Google Sign-In với iOS.
- Thêm chương trình URL tùy chỉnh cho dự án Xcode của bạn:
- Mở cấu hình dự án của bạn: kích đúp vào tên dự án trong màn hình cây trái. Chọn ứng dụng của bạn từ phần MỤC TIÊU, sau đó chọn tab Info, và mở rộng phần loại URL.
- Nhấp vào nút +, và thêm một thức truy cập URL cho ID khách hàng đảo ngược của bạn. Để tìm giá trị này, mở
tập tin cấu hình, và nhìn choGoogleService-Info.plist REVERSED_CLIENT_ID
then chốt. Sao chép giá trị của key đó, và dán nó vào URL Schemes hộp tìm kiếm trên trang cấu hình. Rời khỏi lĩnh vực trống khác.Khi hoàn thành, cấu hình của bạn sẽ giống tương tự như sau (nhưng với các giá trị riêng cho ứng dụng):
- Trong đại biểu ứng dụng của bạn
application:didFinishLaunchingWithOptions:
phương pháp, cấu hìnhFirebaseApp
đối tượng.Nhanh
// Use Firebase library to configure APIs FirebaseApp.configure()
Objective-C
// Use Firebase library to configure APIs [FIRApp configure];
- Thực hiện các
application:openURL:options:
phương pháp đại biểu ứng dụng của bạn. Phương pháp này nên gọihandleURL
phương pháp củaGIDSignIn
dụ, mà sẽ xử lý đúng đắn các URL mà ứng dụng của bạn nhận được vào cuối của quá trình xác thực.Nhanh
@available(iOS 9.0, *) func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool { return GIDSignIn.sharedInstance.handle(url) }
Objective-C
- (BOOL)application:(nonnull UIApplication *)application openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<NSString *, id> *)options { return [[GIDSignIn sharedInstance] handleURL:url]; }
- Vượt qua điều khiển xem trình bày và ID khách hàng cho ứng dụng của bạn với Google Đăng nhập đăng nhập phương pháp và tạo ra một căn cứ hỏa lực auth chứng từ kết quả của Google auth mã thông báo:
Nhanh
guard let clientID = FirebaseApp.app()?.options.clientID else { return } // Create Google Sign In configuration object. let config = GIDConfiguration(clientID: clientID) // Start the sign in flow! GIDSignIn.sharedInstance.signIn(with: config, presenting: self) { [unowned self] user, error in if let error = error { // ... return } guard let authentication = user?.authentication, let idToken = authentication.idToken else { return } let credential = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: authentication.accessToken) // ... }
Objective-C
GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:[FIRApp defaultApp].options.clientID]; __weak __auto_type weakSelf = self; [GIDSignIn.sharedInstance signInWithConfiguration:config presentingViewController:self callback:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) { __auto_type strongSelf = weakSelf; if (strongSelf == nil) { return; } if (error == nil) { GIDAuthentication *authentication = user.authentication; FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken accessToken:authentication.accessToken]; // ... } else { // ... } }];
- Thêm một
GIDSignInButton
vào bảng phân cảnh của bạn, tập tin XIB, hoặc nhanh chóng nó lập trình. Để thêm nút vào bảng phân cảnh của bạn hoặc tập tin XIB, thêm một Xem và thiết lập lớp tùy chỉnh nó đểGIDSignInButton
. - Tùy chọn: Nếu bạn muốn tùy chỉnh các nút, làm như sau:
Nhanh
- Trong điều khiển xem của bạn, kê khai đăng nhập nút như một tài sản.
@IBOutlet weak var signInButton: GIDSignInButton!
- Kết nối vào nút để các
signInButton
tài sản mà bạn vừa khai báo. - Tùy chỉnh các nút bằng cách thiết lập các thuộc tính của GIDSignInButton đối tượng.
Objective-C
- Trong phần đầu tập tin điều khiển quan điểm của bạn, kê khai đăng nhập nút như một tài sản.
@property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
- Kết nối vào nút để các
signInButton
tài sản mà bạn vừa khai báo. - Tùy chỉnh các nút bằng cách thiết lập các thuộc tính của GIDSignInButton đối tượng.
- Trong điều khiển xem của bạn, kê khai đăng nhập nút như một tài sản.
3. Authenticate với căn cứ hỏa lực
Cuối cùng, hoàn tất quá trình đăng nhập căn cứ hỏa lực với chứng chỉ auth tạo ra trong bước trước.
Nhanh
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; // ... }];
Bước tiếp theo
Sau một người dùng đăng nhập lần đầu tiên, một tài khoản người dùng mới được tạo ra và liên quan đến các chứng chỉ-có nghĩa là, tên người dùng và mật khẩu, số điện thoại, hoặc auth cung cấp thông tin người dùng đăng nhập bằng. Tài khoản mới này được lưu giữ như một phần của dự án căn cứ hỏa lực của bạn, và có thể được sử dụng để xác định một người dùng trên mọi ứng dụng trong dự án của bạn, bất kể như thế nào người dùng đăng nhập.
Trong các ứng dụng của bạn, bạn có thể nhận được thông tin hồ sơ cơ bản của người dùng từ các
FIRUser
đối tượng. Xem Quản lý người dùng .Trong Cơ sở dữ liệu căn cứ hỏa lực Realtime của bạn và lưu trữ đám mây Security Rules , bạn có thể nhận được đã đăng nhập của người sử dụng ID người dùng duy nhất từ
auth
biến, và sử dụng nó để kiểm soát dữ liệu 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 sử dụng nhiều nhà cung cấp chứng thực bởi liên kết auth thông tin cung cấp cho một tài khoản người dùng hiện có.
Đăng xuất khỏi một người sử dụng, hãy gọi signOut:
.
Nhanh
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; }
Bạn cũng có thể muốn thêm mã xử lý lỗi cho phạm vi đầy đủ các lỗi xác thực. Xem lỗi Xử lý .