คุณสามารถให้ผู้ใช้ตรวจสอบสิทธิ์กับ Firebase โดยใช้บัญชี Google ของพวกเขาได้โดยการรวม Google Sign-In เข้ากับแอปของคุณ
ก่อนที่คุณจะเริ่มต้น
- เพิ่ม Firebase ในโครงการ Apple ของคุณ รวมพ็อดต่อไปนี้ใน
Podfile
ของคุณ :pod 'FirebaseAuth' pod 'GoogleSignIn'
- หากคุณยังไม่ได้เชื่อมต่อแอปกับโปรเจ็กต์ Firebase ให้เชื่อมต่อจาก คอนโซล Firebase
- เปิดใช้งาน Google เป็นวิธีการลงชื่อเข้าใช้ในคอนโซล Firebase:
- ใน คอนโซล Firebase ให้เปิดส่วนการ รับรอง ความถูกต้อง
- ในแท็บ วิธีการลงชื่อเข้า ใช้ ให้เปิดใช้งานวิธีการลงชื่อเข้าใช้ Google แล้วคลิก บันทึก
1. นำเข้าไฟล์ส่วนหัวที่จำเป็น
ก่อนอื่น คุณต้องนำเข้าไฟล์ส่วนหัว Firebase SDK และ Google Sign-In SDK ลงในแอปของคุณ
สวิฟต์
import FirebaseCore import GoogleSignIn
วัตถุประสงค์-C
@import FirebaseCore; @import GoogleSignIn;
2. ใช้การลงชื่อเข้าใช้ Google
ใช้ Google Sign-In โดยทำตามขั้นตอนเหล่านี้ ดู เอกสารประกอบการลงชื่อเข้าใช้ Google สำหรับนักพัฒนาซอฟต์แวร์ สำหรับรายละเอียดเกี่ยวกับการใช้ Google Sign-In กับ iOS
- เพิ่มรูปแบบ URL ที่กำหนดเองในโครงการ Xcode ของคุณ:
- เปิดการกำหนดค่าโครงการของคุณ: ดับเบิลคลิกที่ชื่อโครงการในมุมมองแบบต้นไม้ด้านซ้าย เลือกแอปของคุณจากส่วน เป้าหมาย จากนั้นเลือกแท็บ ข้อมูล และขยายส่วน ประเภท URL
- คลิกปุ่ม + และเพิ่มรูปแบบ URL สำหรับรหัสไคลเอ็นต์ที่ย้อนกลับของคุณ หากต้องการค้นหาค่านี้ ให้เปิดไฟล์การกำหนดค่า
แล้วมองหาคีย์GoogleService-Info.plist REVERSED_CLIENT_ID
คัดลอกค่าของคีย์นั้น และวางลงในช่อง URL Schemes ในหน้าการกำหนดค่า เว้นช่องอื่นๆ ว่างไว้เมื่อเสร็จแล้ว การกำหนดค่าของคุณควรมีลักษณะดังนี้ (แต่มีค่าเฉพาะแอปพลิเคชันของคุณ):
- ใน
application:didFinishLaunchingWithOptions:
ของผู้รับมอบสิทธิ์แอปของคุณ ให้กำหนดค่าวัตถุFirebaseApp
สวิฟต์
// Use Firebase library to configure APIs FirebaseApp.configure()
วัตถุประสงค์-C
// Use Firebase library to configure APIs [FIRApp configure];
- ใช้
application:openURL:options:
method ของผู้รับมอบสิทธิ์แอปของคุณ เมธอดนี้ควรเรียกเมธอดhandleURL
ของอินสแตนซ์GIDSignIn
ซึ่งจะจัดการ URL ที่แอปพลิเคชันของคุณได้รับอย่างเหมาะสมเมื่อสิ้นสุดกระบวนการตรวจสอบสิทธิ์สวิฟต์
@available(iOS 9.0, *) func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool { return GIDSignIn.sharedInstance.handle(url) }
วัตถุประสงค์-C
- (BOOL)application:(nonnull UIApplication *)application openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<NSString *, id> *)options { return [[GIDSignIn sharedInstance] handleURL:url]; }
- ส่งตัวควบคุมมุมมองการนำเสนอและ ID ไคลเอนต์สำหรับแอปของคุณไปยังวิธีการลงชื่อเข้าใช้ Google Sign In และสร้างข้อมูลรับรองการตรวจสอบ Firebase จากโทเค็นการรับรองความถูกต้องของ Google ที่ได้:
สวิฟต์
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) // ... }
วัตถุประสงค์-C
GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:[FIRApp defaultApp].options.clientID]; [GIDSignIn.sharedInstance setConfiguration:config]; __weak __auto_type weakSelf = self; [GIDSignIn.sharedInstance signInWithPresentingViewController:self completion:^(GIDSignInResult * _Nullable result, NSError * _Nullable error) { __auto_type strongSelf = weakSelf; if (strongSelf == nil) { return; } if (error == nil) { FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken:result.user.idToken.tokenString accessToken:result.user.accessToken.tokenString]; // ... } else { // ... } }];
- เพิ่ม
GIDSignInButton
ลงในกระดานเรื่องราว ไฟล์ XIB หรือสร้างอินสแตนซ์โดยทางโปรแกรม หากต้องการเพิ่มปุ่มลงในกระดานเรื่องราวหรือไฟล์ XIB ให้เพิ่ม View และตั้งค่าคลาสที่กำหนดเองเป็นGIDSignInButton
- ทางเลือก : หากคุณต้องการปรับแต่งปุ่ม ให้ทำดังต่อไปนี้:
สวิฟต์
- ในตัวควบคุมมุมมองของคุณ ให้ประกาศปุ่มลงชื่อเข้าใช้เป็นคุณสมบัติ
@IBOutlet weak var signInButton: GIDSignInButton!
- เชื่อมต่อปุ่มเข้ากับคุณสมบัติ
signInButton
ที่คุณเพิ่งประกาศ - ปรับแต่งปุ่มโดยการตั้งค่าคุณสมบัติของวัตถุ GIDSignInButton
วัตถุประสงค์-C
- ในไฟล์ส่วนหัวของตัวควบคุมมุมมอง ให้ประกาศปุ่มลงชื่อเข้าใช้เป็นคุณสมบัติ
@property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
- เชื่อมต่อปุ่มเข้ากับคุณสมบัติ
signInButton
ที่คุณเพิ่งประกาศ - ปรับแต่งปุ่มโดยการตั้งค่าคุณสมบัติของวัตถุ GIDSignInButton
- ในตัวควบคุมมุมมองของคุณ ให้ประกาศปุ่มลงชื่อเข้าใช้เป็นคุณสมบัติ
3. รับรองความถูกต้องด้วย Firebase
สุดท้าย ทำตามขั้นตอนการเข้าสู่ระบบ Firebase ด้วยข้อมูลประจำตัวรับรองความถูกต้องที่สร้างขึ้นในขั้นตอนก่อนหน้า
สวิฟต์
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 // ... }
วัตถุประสงค์-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; // ... }];
ขั้นตอนถัดไป
หลังจากที่ผู้ใช้ลงชื่อเข้าใช้เป็นครั้งแรก บัญชีผู้ใช้ใหม่จะถูกสร้างขึ้นและเชื่อมโยงกับข้อมูลรับรอง ซึ่งได้แก่ ชื่อผู้ใช้และรหัสผ่าน หมายเลขโทรศัพท์ หรือข้อมูลผู้ให้บริการรับรองความถูกต้อง ซึ่งผู้ใช้ลงชื่อเข้าใช้ด้วย บัญชีใหม่นี้จัดเก็บเป็นส่วนหนึ่งของโปรเจ็กต์ Firebase และสามารถใช้ระบุผู้ใช้ในทุกแอปในโครงการ ไม่ว่าผู้ใช้จะลงชื่อเข้าใช้ด้วยวิธีใดก็ตาม
ในแอปของคุณ คุณสามารถรับข้อมูลโปรไฟล์พื้นฐานของผู้ใช้ได้จากวัตถุ
User
ดู จัดการผู้ใช้ใน กฎความปลอดภัย ของ Firebase Realtime Database และ Cloud Storage คุณสามารถรับ ID ผู้ใช้ที่ไม่ซ้ำกันของผู้ใช้ที่ลงชื่อเข้าใช้จากตัวแปร
auth
ความถูกต้อง และใช้เพื่อควบคุมข้อมูลที่ผู้ใช้สามารถเข้าถึงได้
คุณสามารถอนุญาตให้ผู้ใช้ลงชื่อเข้าใช้แอปของคุณโดยใช้ผู้ให้บริการตรวจสอบสิทธิ์หลายรายโดย เชื่อมโยงข้อมูลประจำตัวของผู้ให้บริการตรวจสอบสิทธิ์กับบัญชีผู้ใช้ที่มีอยู่
หากต้องการออกจากระบบผู้ใช้ ให้เรียก signOut:
สวิฟต์
let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print("Error signing out: %@", signOutError) }
วัตถุประสงค์-C
NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { NSLog(@"Error signing out: %@", signOutError); return; }
คุณอาจต้องการเพิ่มรหัสการจัดการข้อผิดพลาดสำหรับข้อผิดพลาดการตรวจสอบสิทธิ์ทั้งหมด ดู จัดการข้อผิดพลาด