Apple 플랫폼에서 Twitter를 사용하여 인증

Firebase SDK를 통해 엔드 투 엔드 로그인 과정을 실행하는 앱에 일반 OAuth 로그인을 통합하여 사용자가 Twitter와 같은 OAuth 제공업체를 통해 Firebase로 인증하도록 허용할 수 있습니다.

시작하기 전에

Swift Package Manager를 사용해 Firebase 종속 항목을 설치하고 관리하세요.

  1. 앱 프로젝트를 연 상태로 Xcode에서 File(파일) > Add Packages(패키지 추가)로 이동합니다.
  2. 메시지가 표시되면 Firebase Apple 플랫폼 SDK 저장소를 추가합니다.
  3.   https://github.com/firebase/firebase-ios-sdk
  4. Firebase 인증 라이브러리를 선택합니다.
  5. 완료되면 Xcode가 백그라운드에서 자동으로 종속 항목을 확인하고 다운로드하기 시작합니다.

사용자가 Twitter 계정을 통해 로그인하도록 하려면 먼저 Firebase 프로젝트에서 Twitter를 로그인 제공업체로 사용 설정해야 합니다.

  1. Apple 프로젝트에 Firebase를 추가합니다.

  2. Podfile에 다음 포드를 추가합니다.

    pod 'FirebaseAuth'
    

  3. Firebase Console에서 인증 섹션을 엽니다.
  4. 로그인 방법 탭에서 Twitter 제공업체를 사용 설정합니다.
  5. 해당 제공업체의 개발자 콘솔에서 제공되는 API 키API 비밀번호를 제공업체 구성에 추가합니다.
    1. Twitter에서 개발자 애플리케이션으로 앱을 등록하고 앱의 OAuth API 키API 비밀번호를 가져옵니다.
    2. Twitter 앱 구성의 앱 설정 페이지에서 Firebase OAuth 리디렉션 URI(예: my-app-12345.firebaseapp.com/__/auth/handler)가 승인 콜백 URL로 설정되어 있는지 확인합니다.
  6. 저장을 클릭합니다.

Firebase SDK로 로그인 과정 처리

Firebase Apple 플랫폼 SDK로 로그인 과정을 처리하려면 다음 단계를 따르세요.

  1. 다음과 같이 Xcode 프로젝트에 커스텀 URL 스킴을 추가합니다.

    1. 왼쪽 트리 보기에서 프로젝트 이름을 더블클릭하여 프로젝트 구성을 엽니다. 대상 섹션에서 앱을 선택하고 정보 탭을 선택한 후 URL 유형 섹션을 펼칩니다.
    2. + 버튼을 클릭하고 인코딩된 앱 ID를 URL 스키마로 추가합니다. 인코딩된 앱 ID는 Firebase Console의 일반 설정 페이지에 있는 iOS 앱 섹션에서 찾을 수 있습니다. 다른 필드는 비워 둡니다.

      완성된 구성은 다음과 같은 형태이며 애플리케이션별 값이 적용됩니다.

      Xcode의 커스텀 URL 스키마 설정 인터페이스 스크린샷

  2. 제공업체 ID twitter.com을 사용하여 OAuthProvider의 인스턴스를 만듭니다.

    Swift

        var provider = OAuthProvider(providerID: "twitter.com")
        

    Objective-C

        FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"twitter.com"];
        
  3. 선택사항: OAuth 요청과 함께 전송하고자 하는 맞춤 OAuth 매개변수를 추가로 지정합니다.

    Swift

        provider.customParameters = [
          "lang": "fr"
          ]
        

    Objective-C

        [provider setCustomParameters:@{@"lang": @"fr"}];
        

    Twitter가 지원하는 매개변수 정보는 Twitter OAuth 문서를 참조하세요. Firebase에서 요구하는 매개변수는 setCustomParameters와 함께 전달할 수 없습니다. 이러한 매개변수에는 client_id, redirect_uri, response_type, scope, state가 있습니다.

  4. 선택사항: 사용자에게 reCAPTCHA를 제시할 때 앱에서 SFSafariViewController 또는 UIWebView를 표시하는 방식을 맞춤설정하려면 AuthUIDelegate 프로토콜을 준수하는 커스텀 클래스를 만들어 credentialWithUIDelegate에 전달합니다.

  5. OAuth 제공업체 객체를 사용해 Firebase에 인증합니다.

    Swift

        provider.getCredentialWith(nil) { credential, error in
          if error != nil {
            // Handle error.
          }
          if credential != nil {
            Auth.auth().signIn(with: credential) { authResult, error in
              if error != nil {
                // Handle error.
              }
              // User is signed in.
              // IdP data available in authResult.additionalUserInfo.profile.
              // Twitter OAuth access token can also be retrieved by:
              // (authResult.credential as? OAuthCredential)?.accessToken
              // Twitter OAuth ID token can be retrieved by calling:
              // (authResult.credential as? OAuthCredential)?.idToken
              // Twitter OAuth secret can be retrieved by calling:
              // (authResult.credential as? OAuthCredential)?.secret
            }
          }
        }
        

    Objective-C

        [provider getCredentialWithUIDelegate:nil
                                   completion:^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) {
          if (error) {
           // Handle error.
          }
          if (credential) {
            [[FIRAuth auth] signInWithCredential:credential
                                      completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
              if (error) {
                // Handle error.
              }
              // User is signed in.
              // IdP data available in authResult.additionalUserInfo.profile.
              // Twitter OAuth access token can also be retrieved by:
              // authResult.credential.accessToken
              // Twitter OAuth ID token can be retrieved by calling:
              // authResult.credential.idToken
              // Twitter OAuth secret can be retrieved by calling:
              // authResult.credential.secret
            }];
          }
        }];
        

    OAuth 액세스 토큰을 사용하면 Twitter API를 호출할 수 있습니다.

    예를 들어 기본 프로필 정보를 가져오려면 REST API를 호출하여 Authorization 헤더에 액세스 토큰을 전달할 수 있습니다.

    https://api.twitter.com/labs/1/users?usernames=TwitterDev
    
  6. 위의 예시는 로그인 과정에 중점을 두고 있지만 Twitter 제공업체를 기존 사용자에 연결할 수도 있습니다. 예를 들어 여러 제공업체를 동일한 사용자에 연결하여 그중 하나로 로그인하도록 허용할 수 있습니다.

    Swift

        Auth().currentUser.link(withCredential: credential) { authResult, error in
          if error != nil {
            // Handle error.
          }
          // Twitter credential is linked to the current user.
          // IdP data available in authResult.additionalUserInfo.profile.
          // Twitter OAuth access token can also be retrieved by:
          // (authResult.credential as? OAuthCredential)?.accessToken
          // Twitter OAuth ID token can be retrieved by calling:
          // (authResult.credential as? OAuthCredential)?.idToken
          // Twitter OAuth secret can be retrieved by calling:
          // (authResult.credential as? OAuthCredential)?.secret
        }
        

    Objective-C

        [[FIRAuth auth].currentUser
            linkWithCredential:credential
                    completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
          if (error) {
            // Handle error.
          }
          // Twitter credential is linked to the current user.
          // IdP data available in authResult.additionalUserInfo.profile.
          // Twitter OAuth access token is can also be retrieved by:
          // ((FIROAuthCredential *)authResult.credential).accessToken
          // Twitter OAuth ID token can be retrieved by calling:
          // ((FIROAuthCredential *)authResult.credential).idToken
          // Twitter OAuth secret can be retrieved by calling:
          // ((FIROAuthCredential *)authResult.credential).secret
        }];
        
  7. 최근 로그인한 적이 있어야 진행할 수 있는 중요한 작업에 대해 새로운 사용자 인증 정보를 검색하는 데 사용할 수 있는 reauthenticateWithCredential와 동일한 패턴을 사용할 수 있습니다.

    Swift

        Auth().currentUser.reauthenticateWithCredential(withCredential: credential) { authResult, error in
          if error != nil {
            // Handle error.
          }
          // User is re-authenticated with fresh tokens minted and
          // should be able to perform sensitive operations like account
          // deletion and email or password update.
          // IdP data available in result.additionalUserInfo.profile.
          // Additional OAuth access token is can also be retrieved by:
          // (authResult.credential as? OAuthCredential)?.accessToken
          // Twitter OAuth ID token can be retrieved by calling:
          // (authResult.credential as? OAuthCredential)?.idToken
          // Twitter OAuth secret can be retrieved by calling:
          // (authResult.credential as? OAuthCredential)?.secret
        }
        

    Objective-C

        [[FIRAuth auth].currentUser
            reauthenticateWithCredential:credential
                              completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
          if (error) {
            // Handle error.
          }
          // User is re-authenticated with fresh tokens minted and
          // should be able to perform sensitive operations like account
          // deletion and email or password update.
          // IdP data available in result.additionalUserInfo.profile.
          // Additional OAuth access token is can also be retrieved by:
          // ((FIROAuthCredential *)authResult.credential).accessToken
          // Twitter OAuth ID token can be retrieved by calling:
          // ((FIROAuthCredential *)authResult.credential).idToken
          // Twitter OAuth secret can be retrieved by calling:
          // ((FIROAuthCredential *)authResult.credential).secret
        }];
        

다음 단계

사용자가 처음으로 로그인하면 신규 사용자 계정이 생성되고 사용자가 로그인할 때 사용한 사용자 인증 정보(사용자 이름과 비밀번호, 전화번호 또는 인증 제공업체 정보)에 연결됩니다. 이 신규 계정은 Firebase 프로젝트의 일부로 저장되며 사용자의 로그인 방법에 관계없이 프로젝트 내 모든 앱에서 사용자를 식별하는 데 사용될 수 있습니다.

  • 앱의 User 객체에서 사용자의 기본 프로필 정보를 가져올 수 있습니다. 사용자 관리를 참조하세요.

  • Firebase 실시간 데이터베이스와 Cloud Storage 보안 규칙auth 변수에서 로그인한 사용자의 고유 사용자 ID를 가져온 후 이 ID를 사용하여 사용자가 액세스할 수 있는 데이터를 관리할 수 있습니다.

인증 제공업체의 사용자 인증 정보를 기존 사용자 계정에 연결하면 사용자가 여러 인증 제공업체를 통해 앱에 로그인할 수 있습니다.

사용자를 로그아웃시키려면 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;
}

또한 모든 인증 오류에 대한 오류 처리 코드를 추가할 수도 있습니다. 오류 처리를 참조하세요.