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

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

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

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

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

इसके बाद, कॉन्फ़िगरेशन के लिए यह तरीका अपनाएं:

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

Facebook Login लागू करना

Facebook Login के "क्लासिक" वर्शन का इस्तेमाल करने के लिए, यह तरीका अपनाएं. इसके अलावा, अगले सेक्शन में दिखाए गए तरीके से, Facebook Limited Login का इस्तेमाल किया जा सकता है.

  1. डेवलपर दस्तावेज़ में बताए गए निर्देशों का पालन करके, अपने ऐप्लिकेशन में Facebook Login को इंटिग्रेट करें. FBSDKLoginButton ऑब्जेक्ट को शुरू करते समय, लॉगिन और लॉग आउट इवेंट पाने के लिए कोई प्रतिनिधि सेट करें. उदाहरण के लिए:
    SwiftObjective-C
    let loginButton = FBSDKLoginButton()
    loginButton.delegate = self
    FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
    loginButton.delegate = self;
    अपने खाते का ऐक्सेस किसी दूसरे व्यक्ति को देने के लिए, didCompleteWithResult:error: लागू करें.
    SwiftObjective-C
    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
      if let error = error {
        print(error.localizedDescription)
        return
      }
      // ...
    }
    - (void)loginButton:(FBSDKLoginButton *)loginButton
        didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                        error:(NSError *)error {
      if (error == nil) {
        // ...
      } else {
        NSLog(error.localizedDescription);
      }
    }
  2. अपने UIApplicationDelegate में FirebaseCore मॉड्यूल के साथ-साथ, उन सभी Firebase मॉड्यूल को इंपोर्ट करें जिनका इस्तेमाल आपका ऐप्लिकेशन डेलीगेट करता है. उदाहरण के लिए, Cloud Firestore और Authentication का इस्तेमाल करने के लिए:
    SwiftUISwiftObjective-C
    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  3. अपने ऐप्लिकेशन डेलीगेट के application(_:didFinishLaunchingWithOptions:) तरीके में, FirebaseApp शेयर किया गया इंस्टेंस कॉन्फ़िगर करें:
    SwiftUISwiftObjective-C
    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    // Use Firebase library to configure APIs
    [FIRApp configure];
  4. अगर SwiftUI का इस्तेमाल किया जा रहा है, तो आपको एक ऐप्लिकेशन डेलीगेट बनाना होगा और उसे UIApplicationDelegateAdaptor या NSApplicationDelegateAdaptor के ज़रिए अपने App स्ट्रक्चर से अटैच करना होगा. आपको ऐप्लिकेशन डेलीगेट स्विज़लिंग की सुविधा भी बंद करनी होगी. ज़्यादा जानकारी के लिए, 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 क्रेडेंशियल के लिए बदलें:
    SwiftObjective-C
    let credential = FacebookAuthProvider
      .credential(withAccessToken: AccessToken.current!.tokenString)
    FIRAuthCredential *credential = [FIRFacebookAuthProvider
        credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];

Facebook Limited Login लागू करना

"क्लासिक" Facebook Login के बजाय, Facebook Limited Login का इस्तेमाल करने के लिए, यह तरीका अपनाएं.

  1. डेवलपर के दस्तावेज़ में दिए गए निर्देशों का पालन करके, अपने ऐप्लिकेशन में Facebook Limited Login को इंटिग्रेट करें.
  2. हर साइन-इन अनुरोध के लिए, एक यूनीक रैंडम स्ट्रिंग जनरेट करें. इसे "नॉन्स" कहा जाता है. इसका इस्तेमाल, इस बात की पुष्टि करने के लिए किया जाएगा कि आपको जो आईडी टोकन मिला है वह खास तौर पर आपके ऐप्लिकेशन के पुष्टि करने के अनुरोध के जवाब में दिया गया है. रीप्ले हमलों को रोकने के लिए, यह चरण ज़रूरी है. SecRandomCopyBytes(_:_:_) की मदद से, क्रिप्टोग्राफ़िक तरीके से सुरक्षित नॉन्स जनरेट किया जा सकता है. इसका उदाहरण यहां दिया गया है:
    SwiftObjective-C
    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)
    }
    
            
    // 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 की दी गई वैल्यू से करके, रिस्पॉन्स की पुष्टि करता है.
    SwiftObjective-C
    @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
    }
    
            
    - (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 पर सेट करें, और एक नॉन्स अटैच करें. उदाहरण के लिए:
    SwiftObjective-C
    func setupLoginButton() {
        let nonce = randomNonceString()
        currentNonce = nonce
        loginButton.delegate = self
        loginButton.loginTracking = .limited
        loginButton.nonce = sha256(nonce)
    }
            
    - (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: लागू करें.
    SwiftObjective-C
    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
      if let error = error {
        print(error.localizedDescription)
        return
      }
      // ...
    }
            
    - (void)loginButton:(FBSDKLoginButton *)loginButton
        didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                        error:(NSError *)error {
      if (error == nil) {
        // ...
      } else {
        NSLog(error.localizedDescription);
      }
    }
            
  4. अपने UIApplicationDelegate में FirebaseCore मॉड्यूल के साथ-साथ, उन सभी Firebase मॉड्यूल को इंपोर्ट करें जिनका इस्तेमाल आपका ऐप्लिकेशन डेलीगेट करता है. उदाहरण के लिए, Cloud Firestore और Authentication का इस्तेमाल करने के लिए:
    SwiftUISwiftObjective-C
    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  5. अपने ऐप्लिकेशन डेलीगेट के application(_:didFinishLaunchingWithOptions:) तरीके में, FirebaseApp शेयर किया गया इंस्टेंस कॉन्फ़िगर करें:
    SwiftUISwiftObjective-C
    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    // Use Firebase library to configure APIs
    [FIRApp configure];
  6. अगर SwiftUI का इस्तेमाल किया जा रहा है, तो आपको एक ऐप्लिकेशन डेलीगेट बनाना होगा और उसे UIApplicationDelegateAdaptor या NSApplicationDelegateAdaptor के ज़रिए अपने App स्ट्रक्चर से अटैच करना होगा. आपको ऐप्लिकेशन डेलीगेट स्विज़लिंग की सुविधा भी बंद करनी होगी. ज़्यादा जानकारी के लिए, 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: को लागू करने के लिए, Firebase क्रेडेंशियल पाने के लिए, Facebook के रिस्पॉन्स में मौजूद आईडी टोकन का इस्तेमाल करें. इसके लिए, बिना हैश किए गए नॉन्स का इस्तेमाल करें:
    SwiftObjective-C
    // Initialize a Firebase credential.
    let idTokenString = AuthenticationToken.current?.tokenString
    let nonce = currentNonce
    let credential = OAuthProvider.credential(withProviderID: "facebook.com",
                                              idToken: idTokenString!,
                                              rawNonce: nonce)
            
    // 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 से पुष्टि करें:

SwiftObjective-C
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
    // ...
}
    
[[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 सुरक्षा नियमों में, आपके पास auth वैरिएबल से साइन इन किए गए उपयोगकर्ता का यूनीक उपयोगकर्ता आईडी पाने का विकल्प है. साथ ही, इसका इस्तेमाल करके यह कंट्रोल किया जा सकता है कि उपयोगकर्ता कौनसा डेटा ऐक्सेस कर सकता है.

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

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

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

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

Firebase Authentication lets you add an end-to-end identity solution to your app for easy user authentication, sign-in, and onboarding in just a few lines of code.

Mar 7, 2025 को अपडेट किया गया

Firebase Authentication lets you add an end-to-end identity solution to your app for easy user authentication, sign-in, and onboarding in just a few lines of code.

Mar 7, 2025 को अपडेट किया गया