OIDC로 사용자 로그인

이 문서에서는 Identity Platform을 사용하여 OpenID Connect(OIDC) 공급업체로 사용자를 로그인 처리하는 방법을 보여줍니다.

시작하기 전에

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  5. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  6. Identity Platform을 사용 설정하고 클라이언트 SDK를 앱에 추가합니다. 자세한 내용은 빠른 시작을 참조하세요.

공급업체 구성

  1. Google Cloud Console에서 ID 공급업체 페이지로 이동합니다.
    ID 공급업체 페이지로 이동

  2. 공급업체 추가를 클릭하고 목록에서 OpenID Connect를 선택합니다.

승인 코드 흐름

  1. 승인 코드 흐름을 사용 설정하려면 다음 세부정보를 입력합니다.

    1. 부여 유형 선택 섹션에서 코드 흐름을 선택합니다.

    2. 공급업체의 이름. 공급업체 ID 또는 커스텀 이름과 동일할 수 있습니다. 커스텀 이름을 입력할 경우 공급업체 ID 옆에 있는 수정을 클릭하여 ID(oidc.로 시작해야 함)를 지정합니다.

    3. 공급업체의 클라이언트 ID

    4. 공급업체의 발급자. https://example.com과 같이 표시됩니다. Identity Platform은 이 URL을 사용하여 공급업체의 OAuth 엔드포인트와 공개 키를 지정하는 OIDC 검색 문서(일반적으로 /.well-known/openid-configuration에 있음)를 찾습니다.

    5. 공급업체의 클라이언트 보안 비밀번호

  2. 승인된 도메인 목록에 앱을 추가합니다. 예를 들어 앱의 로그인 URL이 https://example.com/login이면 example.com을 추가합니다.

  3. Identity Platform 콜백 URL을 OIDC 공급업체의 리디렉션 URL로 구성합니다. URL은 https://[PROJECT-ID].firebaseapp.com/__/auth/handler와 비슷하게 표시됩니다.

  4. 저장을 클릭합니다.

암시적 흐름

  1. 다음 세부정보를 입력하여 암시적 흐름을 사용 설정합니다.

    1. 부여 유형 선택 섹션에서 암시적 흐름을 선택합니다.

    2. 공급업체의 이름. 공급업체 ID 또는 커스텀 이름과 동일할 수 있습니다. 커스텀 이름을 입력할 경우 공급업체 ID 옆에 있는 수정을 클릭하여 ID(oidc.로 시작해야 함)를 지정합니다.

    3. 공급업체의 클라이언트 ID

    4. 공급업체의 발급자. Identity Platform은 이 URL을 사용하여 공급업체의 OAuth 엔드포인트와 공개 키를 지정하는 OIDC 검색 문서(일반적으로 /.well-known/openid-configuration에 있음)를 찾으므로 이는 https://example.com.과 같아야 합니다.

  2. 승인된 도메인 목록에 앱을 추가합니다. 예를 들어 앱의 로그인 URL이 https://example.com/login이면 example.com을 추가합니다.

  3. Identity Platform 콜백 URL을 OIDC 공급업체의 리디렉션 URL로 구성합니다. URL은 https://[PROJECT-ID].firebaseapp.com/__/auth/handler와 비슷하게 표시됩니다.

  4. 저장을 클릭합니다.

사용자 로그인

OIDC로 사용자를 로그인 처리하는 방법에는 두 가지가 있습니다.

  • OAuth 흐름 사용. 이렇게 하면 OAuth 핸드셰이크가 완료됩니다. 공급업체 구성 단계에서 승인 코드 흐름/암시적 흐름 선택을 기반으로 GCIP 서버는 ID 공급업체와 통신할 원하는 흐름을 선택합니다.

  • OIDC 공급업체의 ID 토큰 사용. 이 방식에서는 이미 OIDC 토큰을 사용할 수 있다고 가정합니다.

OAuth로 사용자 로그인

OAuth를 사용하여 로그인하려면 다음 안내를 따르세요.

  1. 이전 섹션에서 구성한 공급업체 ID로 OAuthProvider 인스턴스를 만듭니다. 공급업체 ID는 oidc.로 시작해야 합니다.

    웹 버전 9

    import { OAuthProvider } from "firebase/auth";
    
    const provider = new OAuthProvider("oidc.myProvider");

    웹 버전 8

    const provider = new firebase.auth.OAuthProvider('oidc.myProvider');
  2. 로그인 과정을 시작합니다. 팝업 또는 리디렉션을 사용하도록 선택할 수 있습니다.

    웹 버전 9

    import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth";
    
    const auth = getAuth();
    signInWithPopup(auth, provider)
      .then((result) => {
        // User is signed in.
        const credential = OAuthProvider.credentialFromResult(result);
        // This gives you an access token for the OIDC provider. You can use it to directly interact with that provider
      }).catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.customData.email;
        // The AuthCredential type that was used.
        const credential = OAuthProvider.credentialFromError(error);
        // Handle / display error.
        // ...
      });

    웹 버전 8

    firebase.auth().signInWithPopup(provider)
      .then((result) => {
        // User is signed in.
        // result.credential is a firebase.auth().OAuthCredential object.
        // result.credential.providerId is equal to 'oidc.myProvider'.
        // result.credential.idToken is the OIDC provider's ID token.
      })
      .catch((error) => {
        // Handle error.
      });

    리디렉션

    로그인 페이지로 리디렉션하려면 signInWithRedirect()를 호출합니다.

    웹 버전 9

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

    웹 버전 8

    firebase.auth().signInWithRedirect(provider).catch((error) => {
      // Handle error.
    });

    그런 다음 getRedirectResult()를 호출하여 사용자가 앱으로 돌아올 때 결과를 가져옵니다.

    웹 버전 9

    import { getAuth, getRedirectResult, OAuthProvider } from "firebase/auth";
    
    const auth = getAuth();
    getRedirectResult(auth)
      .then((result) => {
        // User is signed in.
        const credential = OAuthProvider.credentialFromResult(result);
        // This gives you an access token for the OIDC provider. You can use it to directly interact with that provider
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.customData.email;
        // The AuthCredential type that was used.
        const credential = OAuthProvider.credentialFromError(error);
        // Handle / display error.
        // ...
      });

    웹 버전 8

    // On return.
    firebase.auth().getRedirectResult()
      .then((result) => {
        // User is signed in.
        // result.credential is a firebase.auth().OAuthCredential object.
        // result.credential.providerId is equal to 'oidc.myProvider'.
        // result.credential.idToken is the OIDC provider's ID token.
      })
      .catch((error) => {
        // Handle / display error.
        // ...
      });

각 흐름이 끝나면 result.credential.idToken 필드를 사용하여 OIDC ID 토큰을 가져올 수 있습니다.

사용자 직접 로그인

OIDC ID 토큰으로 사용자를 로그인 처리하려면 다음을 수행합니다.

  1. 이전 섹션에서 구성한 공급업체 ID로 OAuthProvider 인스턴스를 초기화합니다. 공급업체 ID는 oidc.로 시작해야 합니다. 그런 다음 OAuthCredential을 만들고 signInWithCredential()을 호출하여 사용자를 로그인 처리합니다.

    웹 버전 9

    import { getAuth, OAuthProvider, signInWithCredential } from "firebase/auth";
    
    const auth = getAuth();
    const credential = provider.credential({
      idToken: oidcIdToken,
    });
    signInWithCredential(auth, credential)
      .then((result) => {
        // User is signed in.
        const newCredential = OAuthProvider.credentialFromResult(result);
        // This gives you a new access token for the OIDC provider. You can use it to directly interact with that provider.
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.customData.email;
        // The AuthCredential type that was used.
        const credential = OAuthProvider.credentialFromError(error);
        // Handle / display error.
        // ...
      });

    웹 버전 8

    const credential = provider.credential(oidcIdToken, null);
    
    firebase.auth().signInWithCredential(credential)
      .then((result) => {
        // User is signed in.
        // User now has a odic.myProvider UserInfo in providerData.
      })
      .catch((error) => {
        // Handle / display error.
        // ...
      });

사용자 계정 연결

사용자가 이미 다른 방식(예: 이메일/비밀번호)을 사용하여 앱에 로그인한 경우 linkWithPopup() 또는 linkWithRedirect()를 사용하여 OIDC 제공업체에 기존 계정을 연결할 수 있습니다. 예를 들어 Google 계정에 연결할 수 있습니다.

웹 버전 9

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

const auth = getAuth();
linkWithPopup(auth.currentUser, provider).then((result) => {
  // Accounts successfully linked.
  const credential = GoogleAuthProvider.credentialFromResult(result);
  const user = result.user;
  // ...
}).catch((error) => {
  // Handle Errors here.
  // ...
});

웹 버전 8

auth.currentUser.linkWithPopup(provider).then((result) => {
  // Accounts successfully linked.
  var credential = result.credential;
  var user = result.user;
  // ...
}).catch((error) => {
  // Handle Errors here.
  // ...
});

다음 단계