자바스크립트에서 GitHub를 사용하여 인증

앱에 GitHub 인증을 통합하여 사용자가 GitHub 계정을 통해 Firebase에 인증하도록 할 수 있습니다. GitHub 인증을 통합하려면 Firebase SDK를 사용해 로그인 과정을 진행해도 되고, GitHub OAuth 2.0 과정을 수동으로 진행하고 그 결과인 액세스 토큰을 Firebase에 전달해도 됩니다.

시작하기 전에

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

Firebase SDK로 로그인 과정 처리

웹 앱을 개발하는 경우 GitHub 계정을 통해 Firebase에 사용자를 인증하는 가장 쉬운 방법은 Firebase 자바스크립트 SDK로 로그인 과정을 처리하는 것입니다. Node.js 또는 브라우저가 아닌 환경에서 사용자를 인증하려면 로그인 과정을 직접 처리해야 합니다.

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

  1. 다음과 같이 GitHub 제공업체 객체의 인스턴스를 생성합니다.
    WebWeb
    import { GithubAuthProvider } from "firebase/auth";
    
    const provider = new GithubAuthProvider();
    var provider = new firebase.auth.GithubAuthProvider();
  2. 선택사항: 인증 제공업체에 요청하고자 하는 OAuth 2.0 범위를 추가로 지정합니다. 범위를 추가하려면 addScope를 호출합니다. 예를 들면 다음과 같습니다.
    WebWeb
    provider.addScope('repo');
    provider.addScope('repo');
    인증 제공업체 문서를 참조하세요.
  3. 선택사항: OAuth 요청과 함께 전송할 커스텀 OAuth 제공업체 매개변수를 추가로 지정합니다. 커스텀 매개변수를 추가하려면 OAuth 제공업체 문서에 지정된 키가 포함된 객체와 해당 값을 사용하여 초기화된 제공업체에서 setCustomParameters를 호출합니다. 예를 들면 다음과 같습니다.
    WebWeb
    provider.setCustomParameters({
      'allow_signup': 'false'
    });
    provider.setCustomParameters({
      'allow_signup': 'false'
    });
    예약된 필수 OAuth 매개변수는 허용되지 않으며 무시됩니다. 자세한 내용은 인증 제공업체 참조를 확인하세요.
  4. GitHub 제공업체 객체를 사용해 Firebase 인증을 진행합니다. 팝업 창을 띄우거나 로그인 페이지로 리디렉션하여 사용자가 GitHub 계정에 로그인하도록 유도할 수 있습니다. 휴대기기의 경우 리디렉션을 사용할 것을 권장합니다.
    • 팝업 창을 사용하여 로그인하려면 signInWithPopup을 호출합니다.
      WebWeb
      import { getAuth, signInWithPopup, GithubAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      signInWithPopup(auth, provider)
        .then((result) => {
          // This gives you a GitHub Access Token. You can use it to access the GitHub API.
          const credential = GithubAuthProvider.credentialFromResult(result);
          const token = credential.accessToken;
      
          // The signed-in user info.
          const user = result.user;
          // IdP data available using getAdditionalUserInfo(result)
          // ...
        }).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 = GithubAuthProvider.credentialFromError(error);
          // ...
        });
      firebase
        .auth()
        .signInWithPopup(provider)
        .then((result) => {
          /** @type {firebase.auth.OAuthCredential} */
          var credential = result.credential;
      
          // This gives you a GitHub Access Token. You can use it to access the GitHub API.
          var token = credential.accessToken;
      
          // The signed-in user info.
          var user = result.user;
          // IdP data available in result.additionalUserInfo.profile.
            // ...
        }).catch((error) => {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
          // ...
        });
      또한 GitHub 제공업체의 OAuth 토큰을 검색하여 GitHub API를 통해 추가 데이터를 가져올 수도 있습니다.

      이 시점에 오류를 파악해서 처리할 수도 있습니다. 오류 코드 목록은 인증 참고 문서에서 확인할 수 있습니다.

    • 로그인 페이지로 리디렉션해서 로그인 과정을 진행하려면 signInWithRedirect를 호출합니다. `signInWithRedirect`를 사용할 때는 권장사항을 따르세요.
      WebWeb
      import { getAuth, signInWithRedirect } from "firebase/auth";
      
      const auth = getAuth();
      signInWithRedirect(auth, provider);
      firebase.auth().signInWithRedirect(provider);
      그러면 페이지가 로드될 때 getRedirectResult를 호출하여 GitHub 제공업체의 OAuth 토큰을 가져올 수도 있습니다.
      WebWeb
      import { getAuth, getRedirectResult, GithubAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      getRedirectResult(auth)
        .then((result) => {
          const credential = GithubAuthProvider.credentialFromResult(result);
          if (credential) {
            // This gives you a GitHub Access Token. You can use it to access the GitHub API.
            const token = credential.accessToken;
            // ...
          }
      
          // The signed-in user info.
          const user = result.user;
          // IdP data available using getAdditionalUserInfo(result)
          // ...
        }).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 = GithubAuthProvider.credentialFromError(error);
          // ...
        });
      firebase.auth()
        .getRedirectResult()
        .then((result) => {
          if (result.credential) {
            /** @type {firebase.auth.OAuthCredential} */
            var credential = result.credential;
      
            // This gives you a GitHub Access Token. You can use it to access the GitHub API.
            var token = credential.accessToken;
            // ...
          }
      
          // The signed-in user info.
          var user = result.user;
          // IdP data available in result.additionalUserInfo.profile.
            // ...
        }).catch((error) => {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
          // ...
        });
      이 단계에서 오류를 파악해서 처리할 수도 있습니다. 오류 코드 목록은 인증 참고 문서에서 확인할 수 있습니다.

Firebase Console에서 이메일 주소당 계정 한 개를 사용 설정한 경우 다른 Firebase 사용자의 제공업체(예: Google)에 이미 존재하는 이메일을 사용하여 GitHub와 같은 제공업체에 로그인을 시도하면 임시 AuthCredential 객체(GitHub 사용자 인증 정보)와 함께 auth/account-exists-with-different-credential 오류가 발생합니다. 사용자가 해당 제공업체에 로그인하려면 먼저 기존 제공업체(Google)에 로그인한 다음 신규 제공업체의 AuthCredential(GitHub 액세스 토큰)에 연결해야 합니다.

signInWithPopup을 사용하는 경우 다음 예시와 같은 코드를 사용해 auth/account-exists-with-different-credential 오류를 처리할 수 있습니다.

import {
  getAuth,
  linkWithCredential,
  signInWithPopup,
  GitHubAuthProvider,
} from "firebase/auth";

try {
  // Step 1: User tries to sign in using GitHub.
  let result = await signInWithPopup(getAuth(), new GitHubAuthProvider());
} catch (error) {
  // Step 2: User's email already exists.
  if (error.code === "auth/account-exists-with-different-credential") {
    // The pending GitHub credential.
    let pendingCred = error.credential;

    // Step 3: Save the pending credential in temporary storage,

    // Step 4: Let the user know that they already have an account
    // but with a different provider, and let them choose another
    // sign-in method.
  }
}

// ...

try {
  // Step 5: Sign the user in using their chosen method.
  let result = await signInWithPopup(getAuth(), userSelectedProvider);

  // Step 6: Link to the GitHub credential.
  // TODO: implement `retrievePendingCred` for your app.
  let pendingCred = retrievePendingCred();

  if (pendingCred !== null) {
    // As you have access to the pending credential, you can directly call the
    // link method.
    let user = await linkWithCredential(result.user, pendingCred);
  }

  // Step 7: Continue to app.
} catch (error) {
  // ...
}

리디렉션 모드

리디렉션 모드에서도 오류를 비슷한 방식으로 처리하지만, 페이지 리디렉션이 이루어지기 전에 대기 중인 사용자 인증 정보를 캐시에 저장해야 한다는 차이점이 있습니다(예: 세션 스토리지 사용).

수동으로 로그인 과정 처리

GitHub 계정을 사용해 Firebase에 인증할 때는 GitHub OAuth 2.0 엔드포인트를 호출하여 로그인 과정을 처리하는 방법도 있습니다.

  1. 개발자 문서를 참고해 앱에 GitHub 인증을 통합합니다. GitHub 로그인 과정의 끝에서 OAuth 2.0 액세스 토큰을 받을 수 있습니다.
  2. Node.js 애플리케이션에 로그인해야 하는 경우 Node.js 애플리케이션에 OAuth 액세스 토큰을 전송합니다.
  3. 사용자가 GitHub에 정상적으로 로그인한 후에 OAuth 2.0 액세스 토큰을 Firebase 사용자 인증 정보로 바꿉니다.
    WebWeb
    import { GithubAuthProvider } from "firebase/auth";
    
    const credential = GithubAuthProvider.credential(token);
    var credential = firebase.auth.GithubAuthProvider.credential(token);
  4. Firebase 사용자 인증 정보를 사용해 Firebase에 인증합니다.
    WebWeb
    import { getAuth, signInWithCredential } from "firebase/auth";
    
    // Sign in with the credential from the user.
    const auth = getAuth();
    signInWithCredential(auth, credential)
      .then((result) => {
        // Signed in 
        // ...
      })
      .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;
        // ...
      });
    // Sign in with the credential from the user.
    firebase.auth()
      .signInWithCredential(credential)
      .then((result) => {
        // Signed in 
        // ...
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // ...
      });

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

Chrome 확장 프로그램 앱을 빌드하는 경우에는 오프스크린 문서 가이드를 참조하세요.

프로젝트를 만들 때 Firebase에서는 프로젝트의 고유한 하위 도메인(https://my-app-12345.firebaseapp.com)을 프로비저닝합니다.

이 도메인은 OAuth 로그인을 위한 리디렉션 메커니즘으로도 사용됩니다. 이 도메인은 지원되는 모든 OAuth 제공업체에 대해 허용되어야 합니다. 하지만 이로 인해 사용자는 애플리케이션으로 다시 리디렉션되기 전에 GitHub에 로그인하는 과정에서 이 도메인을 볼 수 있습니다. 다음으로 이동: https://my-app-12345.firebaseapp.com

하위 도메인이 표시되지 않게 하려면 Firebase Hosting으로 커스텀 도메인을 설정하면 됩니다.

  1. Hosting용 도메인 설정의 1~3단계를 따릅니다. 도메인 소유권을 확인하면 Hosting에서 커스텀 도메인의 SSL 인증서를 프로비저닝합니다.
  2. Firebase Console에서 승인된 도메인 목록에 커스텀 도메인 auth.custom.domain.com을 추가합니다.
  3. GitHub 개발자 콘솔 또는 OAuth 설정 페이지에서 커스텀 도메인 https://auth.custom.domain.com/__/auth/handler에서 액세스할 수 있는 리디렉션 페이지의 URL을 허용 목록에 추가합니다.
  4. 자바스크립트 라이브러리를 초기화할 때는 authDomain 필드를 사용하여 커스텀 도메인을 지정합니다.
    var config = {
      apiKey: '...',
      // Changed from 'PROJECT_ID.firebaseapp.com'.
      authDomain: 'auth.custom.domain.com',
      databaseURL: 'https://PROJECT_ID.firebaseio.com',
      projectId: 'PROJECT_ID',
      storageBucket: 'PROJECT_ID.firebasestorage.app',
      messagingSenderId: 'SENDER_ID'
    };
    firebase.initializeApp(config);

다음 단계

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

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

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

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

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

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

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