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

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

시작하기 전에

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

  1. Apple 프로젝트에 Firebase를 추가합니다.
  2. Firebase Console에서 인증 섹션을 엽니다.
  3. 로그인 방법 탭에서 Microsoft 제공업체를 사용 설정합니다.
  4. 해당 제공업체의 개발자 콘솔에서 제공되는 클라이언트 ID클라이언트 보안 비밀번호를 제공업체 구성에 추가합니다.
    1. Microsoft OAuth 클라이언트를 등록하려면 빠른 시작: Azure Active Directory v2.0 엔드포인트를 사용하여 앱 등록의 안내를 따릅니다. 이 엔드포인트는 Microsoft 개인 계정과 Azure Active Directory 계정을 사용하는 로그인을 지원합니다. Azure Active Directory v2.0 자세히 알아보기
    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 microsoft.com을 사용하여 OAuthProvider의 인스턴스를 만듭니다.

    Swift

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

    Objective-C

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

    Swift

        provider.customParameters = [
          "prompt": "consent",
          "login_hint": "user@firstadd.onmicrosoft.com"
        ]
        

    Objective-C

        [provider setCustomParameters:@{@"prompt": @"consent", @"login_hint": @"user@firstadd.onmicrosoft.com"}];
        

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

    특정 Azure AD 테넌트의 사용자만 애플리케이션에 로그인하도록 허용하려면 Azure AD 테넌트의 도메인 이름 또는 테넌트의 GUID 식별자를 사용하면 됩니다. 맞춤 매개변수 객체의 '테넌트' 필드를 지정하여 수행합니다.

    Swift

        provider.customParameters = [
          // Optional "tenant" parameter in case you are using an Azure AD
          // tenant. eg. '8eaef023-2b34-4da1-9baa-8bc8c9d6a490' or
          // 'contoso.onmicrosoft.com' or "common" for tenant-independent
          // tokens. The default value is "common".
          "tenant": "TENANT_ID"
        ]
        

    Objective-C

        // Optional "tenant" parameter in case you are using an Azure AD tenant.
        // eg. '8eaef023-2b34-4da1-9baa-8bc8c9d6a490' or
        // 'contoso.onmicrosoft.com' or "common" for tenant-independent tokens.
        // The default value is "common".
        provider.customParameters = @{@"tenant": @"TENANT_ID"};
        
  4. 선택사항: 인증 제공업체에서 요청하고자 하는 기본 프로필 범위를 넘는 OAuth 2.0 범위를 추가로 지정합니다.

    Swift

        provider.scopes = ["mail.read", "calendars.read"]
        

    Objective-C

        [provider setScopes:@[@"mail.read", @"calendars.read"]];
        

    자세한 내용은 Microsoft 권한 및 동의 문서를 참조하세요.

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

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

    Swift

        // Replace nil with the custom class that conforms to AuthUIDelegate
        // you created in last step to use a customized web view.
        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.
              // OAuth access token can also be retrieved:
              // (authResult.credential as? OAuthCredential)?.accessToken
              // OAuth ID token can also be retrieved:
              // (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.
              // OAuth access token can also be retrieved:
              // ((FIROAuthCredential *)authResult.credential).accessToken
              // OAuth ID token can also be retrieved:
              // ((FIROAuthCredential *)authResult.credential).idToken
            }];
          }
        }];
        

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

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

    https://graph.microsoft.com/v1.0/me
    

    Firebase 인증에서 지원하는 다른 제공업체와 달리, Microsoft는 사진 URL을 제공하지 않고 대신 Microsoft Graph API를 통해 프로필 사진의 바이너리 데이터를 요청하게 됩니다.

    OAuth 액세스 토큰 외에도 사용자의 OAuth ID 토큰OAuthCredential 객체에서 가져올 수 있습니다. ID 토큰의 sub 클레임은 앱별로 적용되며 Firebase Auth에서 사용하고 user.providerData[0].uid에서 액세스할 수 있는 제휴 사용자 식별자와 일치하지 않습니다. 대신 oid 클레임 필드를 사용해야 합니다. Azure AD 테넌트를 사용하여 로그인할 때는 oid 클레임이 정확히 일치합니다. 하지만 테넌트 외의 케이스에서는 oid 필드가 패딩됩니다. 제휴 ID 4b2eabcdefghijkl의 경우 oid00000000-0000-0000-4b2e-abcdefghijkl 양식이 사용됩니다.

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

    Swift

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

    Objective-C

        [[FIRAuth auth].currentUser
            linkWithCredential:credential
                    completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
          if (error) {
            // Handle error.
          }
          // Microsoft credential is linked to the current user.
          // IdP data available in authResult.additionalUserInfo.profile.
          // OAuth access token can also be retrieved:
          // ((FIROAuthCredential *)authResult.credential).accessToken
          // OAuth ID token can also be retrieved:
          // ((FIROAuthCredential *)authResult.credential).idToken
        }];
        
  8. 최근 로그인한 적이 있어야 진행할 수 있는 중요한 작업에 대해 새로운 사용자 인증 정보를 검색하는 데 사용할 수 있는 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 can also be retrieved:
          // (authResult.credential as? OAuthCredential)?.accessToken
          // OAuth ID token can also be retrieved:
          // (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 can also be retrieved:
          // ((FIROAuthCredential *)authResult.credential).accessToken
          // OAuth ID token can also be retrieved:
          // ((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;
}

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