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

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

시작하기 전에

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

  1. Apple 프로젝트에 Firebase를 추가합니다.
  2. Firebase Console에서 인증 섹션을 엽니다.
  3. 로그인 방법 탭에서 Yahoo 제공업체를 사용 설정합니다.
  4. 해당 제공업체의 개발자 콘솔에서 제공되는 클라이언트 ID클라이언트 보안 비밀번호를 제공업체 구성에 추가합니다.
    1. Yahoo OAuth 클라이언트를 등록하려면 Yahoo에 웹 애플리케이션을 등록하는 방법에 대한 Yahoo 개발자 문서를 따릅니다.

      OpenID Connect API 권한 2개(profileemail)를 선택해야 합니다.

    2. 이러한 제공업체에 앱을 등록할 때 프로젝트의 *.firebaseapp.com 도메인을 앱의 리디렉션 도메인으로 등록해야 합니다.
  5. 저장을 클릭합니다.

Firebase SDK로 로그인 과정 처리

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

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

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

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

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

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

    Swift

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

    Objective-C

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

    Swift

    provider.customParameters = [
    "prompt": "login",
    "language": "fr"
    ]
        

    Objective-C

    [provider setCustomParameters:@{@"prompt": @"login", @"language": @"fr"}];
        

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

  4. 선택사항: 인증 제공업체에서 요청하고자 하는 profileemail 범위를 넘는 OAuth 2.0 범위를 추가로 지정합니다. 애플리케이션에서 Yahoo API의 비공개 사용자 데이터에 대한 액세스가 필요한 경우 Yahoo 개발자 콘솔의 API 권한에서 Yahoo API에 대한 권한을 요청해야 합니다. 요청받은 OAuth 범위는 앱의 API 권한에서 사전 구성된 범위와 정확하게 일치해야 합니다. 예를 들어 사용자 연락처에 읽기/쓰기 액세스 권한이 요청되고 앱의 API 권한에서 사전 구성되었다면 읽기 전용 OAuth 범위 sdct-r 대신 sdct-w를 전달해야 합니다. 그렇지 않으면 과정이 실패하고 최종 사용자에게 오류가 표시됩니다.

    Swift

    // Request access to Yahoo Mail API.
    // Request read/write access to user contacts.
    // This must be preconfigured in the app's API permissions.
    provider.scopes = ["mail-r", "sdct-w"]
        

    Objective-C

    // Request access to Yahoo Mail API.
    // Request read/write access to user contacts.
    // This must be preconfigured in the app's API permissions.
    [provider setScopes:@[@"mail-r", @"sdct-w"]];
        

    자세한 내용은 Yahoo 범위 문서를 참조하세요.

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

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

    Swift

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

    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.
      // Yahoo OAuth access token can also be retrieved by:
      // ((FIROAuthCredential *)authResult.credential).accessToken
      // Yahoo OAuth ID token can be retrieved by calling:
      // ((FIROAuthCredential *)authResult.credential).idToken
    }];
    }
    }];
        

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

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

    https://social.yahooapis.com/v1/user/YAHOO_USER_UID/profile?format=json
    

    여기서 YAHOO_USER_UIDAuth.auth.currentUser.providerData[0].uid 필드 또는 authResult.additionalUserInfo.profile에서 검색할 수 있는 Yahoo 사용자의 ID입니다.

  7. 위의 예시는 로그인 과정에 중점을 두고 있지만 linkWithPopup를 사용하여 Yahoo 제공업체를 기존 사용자에 연결할 수도 있습니다. 예를 들어 여러 제공업체를 동일한 사용자에 연결하여 그 중 하나로 로그인하도록 허용할 수 있습니다.

    Swift

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

    Objective-C

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

    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
    // Yahoo OAuth ID token can be retrieved by calling:
    // (authResult.credential as? OAuthCredential)?.idToken
    }
        

    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
    // Yahoo OAuth ID token can be retrieved by calling:
    // ((FIROAuthCredential *)authResult.credential).idToken
    }];
        

다음 단계

사용자가 처음으로 로그인하면 신규 사용자 계정이 생성되고 사용자가 로그인할 때 사용한 사용자 인증 정보(사용자 이름과 비밀번호, 전화번호 또는 인증 제공업체 정보)에 연결됩니다. 이 신규 계정은 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;
}

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