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

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

वेब कंटेनर इंस्टॉल करने से पहले

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. इसके बाद, पक्का करें कि प्रॉडक्ट सेटिंग > Facebook लॉगिन कॉन्फ़िगरेशन में, डेवलपर के लिए Facebook साइट पर आपके Facebook ऐप्लिकेशन के सेटिंग पेज पर, OAuth रीडायरेक्ट यूआरआई (जैसे, my-app-12345.firebaseapp.com/__/auth/handler) को आपके OAuth रीडायरेक्ट यूआरआई में से एक के तौर पर शामिल किया गया है.

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. अपने UIApplicationDelegate में FirebaseCore मॉड्यूल को इंपोर्ट करें. साथ ही, ऐसे सभी Firebase मॉड्यूल को इंपोर्ट करें जिनका इस्तेमाल आपके ऐप्लिकेशन का ऐक्सेस मैनेज करता है. उदाहरण के लिए, Cloud Firestore और पुष्टि करने की सुविधा का इस्तेमाल करने के लिए:

    स्विफ़्टयूआई

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

    Swift

    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Objective-C

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

    स्विफ़्टयूआई

    // 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 या NSApplicationDelegateAdaptor की मदद से अपने App स्ट्रक्चर में अटैच करना होगा. आपको ऐप्लिकेशन सौंपने की सुविधा को स्वाइप करने की सुविधा भी बंद करनी होगी. ज़्यादा जानकारी के लिए, 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. अपने UIApplicationDelegate में FirebaseCore मॉड्यूल को इंपोर्ट करें. साथ ही, ऐसे सभी Firebase मॉड्यूल को इंपोर्ट करें जिनका इस्तेमाल आपके ऐप्लिकेशन का ऐक्सेस मैनेज करता है. उदाहरण के लिए, Cloud Firestore और पुष्टि करने की सुविधा का इस्तेमाल करने के लिए:

    स्विफ़्टयूआई

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

    Swift

    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Objective-C

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

    स्विफ़्टयूआई

    // 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 या NSApplicationDelegateAdaptor की मदद से अपने App स्ट्रक्चर में अटैच करना होगा. आपको ऐप्लिकेशन सौंपने की सुविधा को स्वाइप करने की सुविधा भी बंद करनी होगी. ज़्यादा जानकारी के लिए, 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;
}

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