자바스크립트에서 Microsoft를 통해 인증

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

시작하기 전에

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

  1. 자바스크립트 프로젝트에 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 자바스크립트 SDK로 전체 로그인 과정을 처리하면 가장 손쉽게 Microsoft 계정을 통해 Firebase로 사용자를 인증할 수 있습니다.

Firebase 자바스크립트 SDK로 로그인 과정을 처리하려면 다음 단계를 따르세요.

  1. 제공업체 ID microsoft.com을 사용하여 OAuthProvider의 인스턴스를 생성합니다.

    웹 모듈식 API

    import { OAuthProvider } from "firebase/auth";
    
    const provider = new OAuthProvider('microsoft.com');

    웹 네임스페이스화된 API

    var provider = new firebase.auth.OAuthProvider('microsoft.com');
  2. 선택사항: OAuth 요청과 함께 전송하고자 하는 커스텀 OAuth 매개변수를 추가로 지정합니다.

    웹 모듈식 API

    provider.setCustomParameters({
      // Force re-consent.
      prompt: 'consent',
      // Target specific email with login hint.
      login_hint: 'user@firstadd.onmicrosoft.com'
    });

    웹 네임스페이스화된 API

    provider.setCustomParameters({
      // Force re-consent.
      prompt: 'consent',
      // Target specific email with login hint.
      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 식별자를 사용하면 됩니다. 이렇게 하려면 커스텀 매개변수 객체의 '테넌트' 필드를 지정합니다.

    웹 모듈식 API

    provider.setCustomParameters({
      // 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'
    });

    웹 네임스페이스화된 API

    provider.setCustomParameters({
      // 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'
    });
  3. 선택사항: 인증 제공업체에 요청하고자 하는 기본 프로필 범위를 넘는 OAuth 2.0 범위를 추가로 지정합니다.

    provider.addScope('mail.read');
    provider.addScope('calendars.read');
    

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

  4. OAuth 제공업체 객체를 사용해 Firebase로 인증합니다. 팝업 창을 띄우거나 로그인 페이지로 리디렉션하여 사용자가 Microsoft 계정으로 로그인하도록 유도할 수 있습니다. 휴대기기의 경우 리디렉션을 사용할 것을 권장합니다.

    • 팝업 창을 사용하여 로그인 과정을 진행하려면 signInWithPopup을 호출합니다.

    웹 모듈식 API

    import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth";
    
    const auth = getAuth();
    signInWithPopup(auth, provider)
      .then((result) => {
        // User is signed in.
        // IdP data available in result.additionalUserInfo.profile.
    
        // Get the OAuth access token and ID Token
        const credential = OAuthProvider.credentialFromResult(result);
        const accessToken = credential.accessToken;
        const idToken = credential.idToken;
      })
      .catch((error) => {
        // Handle error.
      });

    웹 네임스페이스화된 API

    firebase.auth().signInWithPopup(provider)
      .then((result) => {
        // IdP data available in result.additionalUserInfo.profile.
        // ...
    
        /** @type {firebase.auth.OAuthCredential} */
        var credential = result.credential;
    
        // OAuth access and id tokens can also be retrieved:
        var accessToken = credential.accessToken;
        var idToken = credential.idToken;
      })
      .catch((error) => {
        // Handle error.
      });
    • 로그인 페이지로 리디렉션해서 로그인 과정을 진행하려면 signInWithRedirect를 호출합니다.

    signInWithRedirect, linkWithRedirect, reauthenticateWithRedirect를 사용할 때는 권장사항을 따르세요.

    웹 모듈식 API

    import { getAuth, signInWithRedirect } from "firebase/auth";
    
    const auth = getAuth();
    signInWithRedirect(auth, provider);

    웹 네임스페이스화된 API

    firebase.auth().signInWithRedirect(provider);

    사용자가 로그인을 완료하고 페이지로 돌아간 후에 getRedirectResult를 호출하여 로그인 결과를 가져올 수 있습니다.

    웹 모듈식 API

    import { getAuth, getRedirectResult, OAuthProvider } from "firebase/auth";
    
    const auth = getAuth();
    getRedirectResult(auth)
      .then((result) => {
        // User is signed in.
        // IdP data available in result.additionalUserInfo.profile.
    
        // Get the OAuth access token and ID Token
        const credential = OAuthProvider.credentialFromResult(result);
        const accessToken = credential.accessToken;
        const idToken = credential.idToken;
      })
      .catch((error) => {
        // Handle error.
      });

    웹 네임스페이스화된 API

    firebase.auth().getRedirectResult()
      .then((result) => {
        // IdP data available in result.additionalUserInfo.profile.
        // ...
    
        /** @type {firebase.auth.OAuthCredential} */
        var credential = result.credential;
    
        // OAuth access and id tokens can also be retrieved:
        var accessToken = credential.accessToken;
        var idToken = credential.idToken;
      })
      .catch((error) => {
        // Handle error.
      });

    성공적으로 완료되면 제공업체에 연결된 OAuth 액세스 토큰을 반환되는 firebase.auth.UserCredential 객체에서 가져올 수 있습니다.

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

    예를 들어 기본 프로필 정보를 가져오려면 다음 REST API를 호출할 수 있습니다.

    curl -i -H "Authorization: Bearer ACCESS_TOKEN" https://graph.microsoft.com/v1.0/me
    

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

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

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

    웹 모듈식 API

    import { getAuth, linkWithPopup, OAuthProvider } from "firebase/auth";
    
    const provider = new OAuthProvider('microsoft.com');
    const auth = getAuth();
    
    linkWithPopup(auth.currentUser, provider)
        .then((result) => {
          // Microsoft credential is linked to the current user.
          // IdP data available in result.additionalUserInfo.profile.
    
          // Get the OAuth access token and ID Token
          const credential = OAuthProvider.credentialFromResult(result);
          const accessToken = credential.accessToken;
          const idToken = credential.idToken;
        })
        .catch((error) => {
          // Handle error.
        });

    웹 네임스페이스화된 API

    var provider = new firebase.auth.OAuthProvider('microsoft.com');
    firebase.auth().currentUser.linkWithPopup(provider)
        .then((result) => {
          // Microsoft credential is linked to the current user.
          // IdP data available in result.additionalUserInfo.profile.
          // OAuth access token can also be retrieved:
          // result.credential.accessToken
          // OAuth ID token can also be retrieved:
          // result.credential.idToken
        })
        .catch((error) => {
          // Handle error.
        });
  6. reauthenticateWithPopup/reauthenticateWithRedirect에도 동일한 패턴을 사용하여 최근에 로그인한 적이 있어야 진행할 수 있는 중요한 작업을 위해 새로운 사용자 인증 정보를 가져올 수 있습니다.

    웹 모듈식 API

    import { getAuth, reauthenticateWithPopup, OAuthProvider } from "firebase/auth";
    
    const provider = new OAuthProvider('microsoft.com');
    const auth = getAuth();
    reauthenticateWithPopup(auth.currentUser, provider)
        .then((result) => {
          // 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.
    
          // Get the OAuth access token and ID Token
          const credential = OAuthProvider.credentialFromResult(result);
          const accessToken = credential.accessToken;
          const idToken = credential.idToken;
        })
        .catch((error) => {
          // Handle error.
        });

    웹 네임스페이스화된 API

    var provider = new firebase.auth.OAuthProvider('microsoft.com');
    firebase.auth().currentUser.reauthenticateWithPopup(provider)
        .then((result) => {
          // 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.
          // OAuth access token can also be retrieved:
          // result.credential.accessToken
          // OAuth ID token can also be retrieved:
          // result.credential.idToken
        })
        .catch((error) => {
          // Handle error.
        });

Chrome 확장 프로그램에서 Firebase 인증

Chrome 확장 프로그램 앱을 빌드하는 경우 Chrome 확장 프로그램 ID를 추가해야 합니다.

  1. Firebase Console에서 프로젝트를 엽니다.
  2. 인증 섹션에서 로그인 방법 페이지를 엽니다.
  3. 승인된 도메인 목록에 다음과 같은 URI를 추가합니다.
    chrome-extension://CHROME_EXTENSION_ID

Chrome 확장 프로그램에서는 HTTP 리디렉션을 사용할 수 없으므로 팝업 작업(signInWithPopup, linkWithPopup, reauthenticateWithPopup)만 사용할 수 있습니다. 인증 팝업이 브라우저 작업 팝업을 취소하므로 브라우저 작업 팝업이 아닌 백그라운드 페이지 스크립트에서 이러한 메서드를 호출해야 합니다. 팝업 메서드는 매니페스트 V2를 사용하는 확장 프로그램에서만 사용할 수 있습니다. 최신 매니페스트 V3은 팝업 작업을 전혀 수행할 수 없는 서비스 워커 형식의 백그라운드 스크립트만 허용합니다.

Chrome 확장 프로그램의 매니페스트 파일에서 https://apis.google.com URL이 content_security_policy 허용 목록에 추가되었는지 확인합니다.

다음 단계

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

  • 앱에서 사용자의 인증 상태를 파악할 때 권장하는 방법은 Auth 객체에 관찰자를 설정하는 것입니다. 그러면 User 객체로부터 사용자의 기본 프로필 정보를 가져올 수 있습니다. 사용자 관리를 참조하세요.

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

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

사용자를 로그아웃시키려면 signOut을 호출합니다.

웹 모듈식 API

import { getAuth, signOut } from "firebase/auth";

const auth = getAuth();
signOut(auth).then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});

웹 네임스페이스화된 API

firebase.auth().signOut().then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});