Apple प्लैटफ़ॉर्म पर Facebook लॉगिन का इस्तेमाल करके पुष्टि करें

आपके पास अपने उपयोगकर्ताओं को उनके Facebook खातों का इस्तेमाल करके, Firebase की मदद से पुष्टि करने की सुविधा देने का विकल्प है अपने ऐप्लिकेशन में Facebook लॉगिन या Facebook सीमित लॉगिन को इंटिग्रेट करके.

शुरू करने से पहले

Firebase डिपेंडेंसी इंस्टॉल और मैनेज करने के लिए, Swift पैकेज मैनेजर का इस्तेमाल करें.

  1. Xcode में, अपना ऐप्लिकेशन प्रोजेक्ट खोलने के लिए, फ़ाइल > पैकेज जोड़ना.
  2. जब कहा जाए, तब Firebase Apple प्लैटफ़ॉर्म SDK टूल का रिपॉज़िटरी जोड़ें:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. Firebase से पुष्टि करने की लाइब्रेरी चुनें.
  5. अपने टारगेट की बिल्ड सेटिंग के अन्य लिंकर फ़्लैग सेक्शन में -ObjC फ़्लैग जोड़ें.
  6. यह काम पूरा होने पर, Xcode अपने-आप रिज़ॉल्व और डाउनलोड होना शुरू कर देगा पर निर्भर करता है.

इसके बाद, कॉन्फ़िगरेशन के कुछ चरण पूरे करें:

  1. Facebook के लिए डेवलपर पर की साइट पर, अपने ऐप्लिकेशन के लिए ऐप्लिकेशन आईडी और ऐप्लिकेशन सीक्रेट पाएं.
  2. Facebook में लॉगिन करने की सुविधा चालू करें:
    1. Firebase कंसोल में, पुष्टि करें सेक्शन खोलें.
    2. साइन इन करने का तरीका टैब पर, Facebook साइन इन की सुविधा चालू करें तरीका और Facebook से मिला ऐप्लिकेशन आईडी और ऐप्लिकेशन सीक्रेट बताएं.
    3. इसके बाद, पक्का करें कि आपका OAuth रीडायरेक्ट यूआरआई (जैसे, my-app-12345.firebaseapp.com/__/auth/handler) आपके OAuth रीडायरेक्ट यूआरआई में से एक के रूप में सूचीबद्ध है Facebook for Developers साइट प्रॉडक्ट सेटिंग > Facebook लॉगिन कॉन्फ़िगरेशन.

Facebook लॉगिन लागू करें

"क्लासिक" इस्तेमाल करने के लिए Facebook लॉगिन करके, नीचे दिए गए चरणों को पूरा करें. इसके अलावा, Facebook लिमिटेड लॉगिन का इस्तेमाल कर सकते हैं, जैसा कि अगले सेक्शन में बताया गया है.

  1. नीचे दिए गए निर्देशों का पालन करके Facebook लॉगिन को अपने ऐप्लिकेशन में इंटिग्रेट करें डेवलपर के दस्तावेज़ में दिए गए हैं. शुरू करने पर FBSDKLoginButton ऑब्जेक्ट, लॉगिन पाने के लिए कोई प्रतिनिधि सेट करें और लॉगआउट इवेंट. उदाहरण के लिए:

    Swift

    let loginButton = FBSDKLoginButton()
    loginButton.delegate = self
    

    Objective-C

    FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
    loginButton.delegate = self;
    
    आपने जिस व्यक्ति को ईमेल खाते का ऐक्सेस दिया है उसमें didCompleteWithResult:error: लागू करें.

    Swift

    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
      if let error = error {
        print(error.localizedDescription)
        return
      }
      // ...
    }
    

    Objective-C

    - (void)loginButton:(FBSDKLoginButton *)loginButton
        didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                        error:(NSError *)error {
      if (error == nil) {
        // ...
      } else {
        NSLog(error.localizedDescription);
      }
    }
    
  2. अपने इसमें FirebaseCore मॉड्यूल को इंपोर्ट करें UIApplicationDelegate और अन्य वे Firebase मॉड्यूल जिनका इस्तेमाल आपका ऐप्लिकेशन मैनेज करने का ऐक्सेस देने वाला व्यक्ति करता है. उदाहरण के लिए, Cloud Firestore और पुष्टि करने की सुविधा का इस्तेमाल करने के लिए:

    SwiftUI

    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Swift

    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Objective-C

    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  3. कॉन्फ़िगर करें FirebaseApp आपके ऐप्लिकेशन डेलिगेट के शेयर किए गए इंस्टेंस में application(_:didFinishLaunchingWithOptions:) तरीका:

    SwiftUI

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Swift

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  4. अगर SwiftUI का इस्तेमाल किया जा रहा है, तो आपको ऐप्लिकेशन का ऐक्सेस देना होगा और उसे अटैच करना होगा UIApplicationDelegateAdaptor के ज़रिए अपने App निर्देश को या NSApplicationDelegateAdaptor. आपको ऐप्लिकेशन सौंपने की सुविधा को स्वाइप करने की सुविधा भी बंद करनी होगी. इसके लिए ज़्यादा जानकारी के लिए, SwiftUI के निर्देश देखें.

    SwiftUI

    @main
    struct YourApp: App {
      // register app delegate for Firebase setup
      @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
      var body: some Scene {
        WindowGroup {
          NavigationView {
            ContentView()
          }
        }
      }
    }
          
  5. किसी उपयोगकर्ता के साइन इन करने के बाद, didCompleteWithResult:error:, उपयोगकर्ता ने साइन-इन किया हो और उसे Firebase क्रेडेंशियल के लिए एक्सचेंज करता हो:

    Swift

    let credential = FacebookAuthProvider
      .credential(withAccessToken: AccessToken.current!.tokenString)
    

    Objective-C

    FIRAuthCredential *credential = [FIRFacebookAuthProvider
        credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
    

Facebook सीमित लॉगिन लागू करें

"क्लासिक" के बजाय Facebook सीमित लॉगिन का इस्तेमाल करने के लिए Facebook में लॉगिन करने की प्रोसेस पूरी हुई यहां दिया गया तरीका अपनाएं.

  1. नीचे दिए गए निर्देशों का पालन करके, अपने ऐप्लिकेशन में Facebook सीमित लॉगिन को इंटिग्रेट करें डेवलपर के दस्तावेज़ में दिए गए हैं.
  2. हर साइन-इन अनुरोध के लिए, एक यूनीक रैंडम स्ट्रिंग—एक "nonce"—जनरेट करें, जो आपको यह पक्का करने के लिए इस्तेमाल करना होगा कि आपको जो आईडी टोकन मिला है वह खास तौर पर पुष्टि करने का अनुरोध करते हैं. यह चरण इसलिए ज़रूरी है, फिर से चलाने के हमलों से बचें. इनकी मदद से, क्रिप्टोग्राफ़िक तौर पर सुरक्षित नॉन्स जनरेट की जा सकती है SecRandomCopyBytes(_:_:_), जैसा कि इस उदाहरण में दिखाया गया है:

    Swift

    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)
    }
    
            

    Objective-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];
    }
            
    आपको अपने साइन-इन अनुरोध के साथ, नॉन्स का SHA-256 हैश भेजना होगा, जो Facebook, जवाब में कोई बदलाव नहीं करेगा. Firebase रिस्पॉन्स के तौर पर, नॉन्स को हैश करके और पास की गई वैल्यू से उसकी तुलना करें Facebook से.

    Swift

    @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
    }
    
            

    Objective-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;
    }
            
  3. FBSDKLoginButton सेट अप करते समय, किसी व्यक्ति को ईमेल खाते का ऐक्सेस दें लॉगिन और लॉगआउट इवेंट पाएं, ट्रैकिंग मोड FBSDKLoginTrackingLimited और नॉन्स अटैच करें. उदाहरण के लिए:

    Swift

    func setupLoginButton() {
        let nonce = randomNonceString()
        currentNonce = nonce
        loginButton.delegate = self
        loginButton.loginTracking = .limited
        loginButton.nonce = sha256(nonce)
    }
            

    Objective-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: लागू करें.

    Swift

    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
      if let error = error {
        print(error.localizedDescription)
        return
      }
      // ...
    }
            

    Objective-C

    - (void)loginButton:(FBSDKLoginButton *)loginButton
        didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                        error:(NSError *)error {
      if (error == nil) {
        // ...
      } else {
        NSLog(error.localizedDescription);
      }
    }
            
  4. अपने इसमें FirebaseCore मॉड्यूल को इंपोर्ट करें UIApplicationDelegate और अन्य वे Firebase मॉड्यूल जिनका इस्तेमाल आपका ऐप्लिकेशन मैनेज करने का ऐक्सेस देने वाला व्यक्ति करता है. उदाहरण के लिए, Cloud Firestore और पुष्टि करने की सुविधा का इस्तेमाल करने के लिए:

    SwiftUI

    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Swift

    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Objective-C

    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  5. कॉन्फ़िगर करें FirebaseApp आपके ऐप्लिकेशन डेलिगेट के शेयर किए गए इंस्टेंस में application(_:didFinishLaunchingWithOptions:) तरीका:

    SwiftUI

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Swift

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  6. अगर SwiftUI का इस्तेमाल किया जा रहा है, तो आपको ऐप्लिकेशन का ऐक्सेस देना होगा और उसे अटैच करना होगा UIApplicationDelegateAdaptor के ज़रिए अपने App निर्देश को या NSApplicationDelegateAdaptor. आपको ऐप्लिकेशन सौंपने की सुविधा को स्वाइप करने की सुविधा भी बंद करनी होगी. इसके लिए ज़्यादा जानकारी के लिए, SwiftUI के निर्देश देखें.

    SwiftUI

    @main
    struct YourApp: App {
      // register app delegate for Firebase setup
      @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
      var body: some Scene {
        WindowGroup {
          NavigationView {
            ContentView()
          }
        }
      }
    }
          
  7. किसी उपयोगकर्ता के साइन इन करने के बाद, didCompleteWithResult:error:, Facebook के आईडी टोकन का इस्तेमाल करें Firebase क्रेडेंशियल पाने के लिए हैश नहीं की गई नॉन्स के साथ प्रतिक्रिया:

    Swift

    // Initialize a Firebase credential.
    let idTokenString = AuthenticationToken.current?.tokenString
    let nonce = currentNonce
    let credential = OAuthProvider.credential(withProviderID: "facebook.com",
                                              idToken: idTokenString!,
                                              rawNonce: nonce)
            

    Objective-C

    // Initialize a Firebase credential.
    NSString *idTokenString = FBSDKAuthenticationToken.currentAuthenticationToken.tokenString;
    NSString *rawNonce = self.currentNonce;
    FIROAuthCredential *credential = [FIROAuthProvider credentialWithProviderID:@"facebook.com"
                                                                        IDToken:idTokenString
                                                                       rawNonce:rawNonce];
            

Firebase की मदद से पुष्टि करें

आखिर में, Firebase क्रेडेंशियल का इस्तेमाल करके, Firebase से पुष्टि करें:

Swift

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;
  // ...
}];
    

अगले चरण

किसी उपयोगकर्ता के पहली बार साइन इन करने के बाद, एक नया उपयोगकर्ता खाता बना दिया जाता है और आपके खाते के क्रेडेंशियल मौजूद हैं, जैसे कि उपयोगकर्ता नाम और पासवर्ड, या पुष्टि करने वाली कंपनी की जानकारी—उपयोगकर्ता ने जिससे साइन इन किया है. यह नया खाते को आपके Firebase प्रोजेक्ट के हिस्से के तौर पर सेव किया जाता है. साथ ही, इसका इस्तेमाल आपके प्रोजेक्ट के हर ऐप्लिकेशन में हर उपयोगकर्ता के लिए उपलब्ध होता है. भले ही, उपयोगकर्ता किसी भी तरह से साइन इन करता हो.

  • अपने ऐप्लिकेशन में, उपयोगकर्ता की बुनियादी प्रोफ़ाइल जानकारी को User ऑब्जेक्ट है. उपयोगकर्ताओं को मैनेज करना देखें.

  • आपके Firebase रीयल टाइम डेटाबेस और Cloud Storage में सुरक्षा नियम, तो auth वैरिएबल से साइन-इन किए हुए उपयोगकर्ता का यूनीक यूज़र आईडी पाएं, और इसका इस्तेमाल करके यह कंट्रोल किया जा सकता है कि उपयोगकर्ता कौनसा डेटा ऐक्सेस कर सकता है.

उपयोगकर्ताओं को, पुष्टि करने के एक से ज़्यादा तरीके का इस्तेमाल करके, अपने ऐप्लिकेशन में साइन इन करने की अनुमति दी जा सकती है पुष्टि करने वाले के क्रेडेंशियल जोड़कर मौजूदा उपयोगकर्ता खाते से लिंक किया जा सकता है.

उपयोगकर्ता को साइन आउट करने के लिए पर कॉल करें signOut:.

Swift

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;
}

ऐसा हो सकता है कि आप पुष्टि करने की पूरी रेंज के लिए, गड़बड़ी मैनेज करने वाला कोड भी जोड़ना चाहें गड़बड़ियां हैं. गड़बड़ियां ठीक करना देखें.