GitHub로 사용자 로그인
이 문서에서는 Identity Platform을 사용하여 GitHub로 사용자를 로그인하는 방법을 보여줍니다.
시작하기 전에
이 튜토리얼에서는 Identity Platform을 이미 사용 설정했으며 HTML 및 자바스크립트를 사용하여 작성된 기본 웹 앱이 있다고 가정합니다. Identity Platform을 사용 설정하고 로그인하는 방법을 알아보려면 빠른 시작을 참고하세요.
GitHub를 공급업체로 구성
GitHub를 ID 공급업체로 구성하려면 다음 안내를 따르세요.
- Google Cloud 콘솔에서 ID 공급업체 페이지로 이동합니다.
- 공급업체 추가를 클릭합니다.
- 목록에서 GitHub를 선택합니다.
- GitHub 클라이언트 ID와 클라이언트 보안 비밀번호를 입력합니다. 아직 ID와 보안 비밀이 없으면 GitHub 애플리케이션 페이지에서 얻을 수 있습니다.
-
GitHub 구성 아래에 나열된 URI를 GitHub 앱의 유효한 OAuth 리디렉션 URI로 구성합니다. Identity Platform에서 커스텀 도메인을 구성한 경우 기본 도메인 대신 커스텀 도메인을 사용하도록 GitHub 앱 구성의 리디렉션 URI를 업데이트합니다. 예를 들어
https://myproject.firebaseapp.com/__/auth/handler
를https://auth.myownpersonaldomain.com/__/auth/handler
로 변경합니다. -
프로젝트 설정 측면 창에서 도메인 추가를 클릭하고 앱의 도메인을 추가합니다.
프로덕션 프로젝트에는
localhost
를 포함하지 않는 것이 좋습니다. - 애플리케이션 구성 섹션에서 설정 세부정보를 클릭합니다. 스니펫을 앱 코드에 복사하여 Identity Platform 클라이언트 SDK를 초기화합니다.
- 저장을 클릭합니다.
클라이언트 SDK로 사용자 로그인
-
다음과 같이 GitHub 제공업체 객체의 인스턴스를 생성합니다.
웹 버전 9
import { GithubAuthProvider } from "firebase/auth"; const provider = new GithubAuthProvider();
웹 버전 8
var provider = new firebase.auth.GithubAuthProvider();
-
선택사항: OAuth 범위를 추가합니다. 범위는 GitHub에서 요청할 데이터를 지정합니다. 더 민감한 정보에는 특정 범위가 필요할 수 있습니다. 앱에 필요한 범위를 확인하려면 공급업체의 문서를 참조하세요.
웹 버전 9
provider.addScope('repo');
웹 버전 8
provider.addScope('repo');
-
선택사항: 인증 흐름을 현지화합니다. 언어를 지정하거나 기기의 기본 언어를 사용할 수 있습니다.
웹 버전 9
import { getAuth } from "firebase/auth"; const auth = getAuth(); auth.languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // auth.useDeviceLanguage();
웹 버전 8
firebase.auth().languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // firebase.auth().useDeviceLanguage();
-
선택사항: 추가적인 커스텀 OAuth 매개변수를 지정합니다. 이는 GitHub에만 해당하며 일반적으로 인증 환경을 맞춤설정하는 데 사용됩니다. OAuth 또는 Identity Platform에서 예약한 매개변수는 전달할 수 없습니다.
웹 버전 9
provider.setCustomParameters({ 'allow_signup': 'false' });
웹 버전 8
provider.setCustomParameters({ 'allow_signup': 'false' });
-
GitHub 공급업체 객체를 사용하여 사용자를 로그인합니다. 팝업 창을 열거나 현재 페이지를 리디렉션할 수 있습니다. 휴대기기에서는 사용자가 리디렉션하기 더 용이합니다.
signInWithPopup()
을 호출하면 팝업이 나타납니다.웹 버전 9
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); // ... });
웹 버전 8
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; // ... });
페이지를 리디렉션하려면 먼저
signInWithRedirect()
를 호출합니다.signInWithRedirect
,linkWithRedirect
,reauthenticateWithRedirect
를 사용할 때는 권장사항을 따르세요.웹 버전 9
import { getAuth, signInWithRedirect } from "firebase/auth"; const auth = getAuth(); signInWithRedirect(auth, provider);
웹 버전 8
firebase.auth().signInWithRedirect(provider);
그런 다음 페이지가 로드될 때
getRedirectResult()
를 호출하여 GitHub 토큰을 검색합니다.웹 버전 9
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); // ... });
웹 버전 8
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; // ... });
액세스 토큰이 있으면 이를 사용하여 GitHub API를 호출할 수 있습니다. 예를 들면 다음과 같습니다.
REST
curl -H "Authorization: Bearer [TOKEN]" https://api.github.com/gists/starred
수동으로 사용자 로그인
클라이언트 SDK를 사용하지 않으려면 로그인 과정을 수동으로 처리할 수도 있습니다.
- 개발자 문서의 단계에 따라 GitHub 인증을 앱에 통합합니다.
- 이전 단계에서 구현한 흐름을 사용하여 GitHub로 사용자를 로그인합니다.
-
GitHub에서 수신한 토큰을 Identity Platform 사용자 인증 정보로 교환합니다.
웹 버전 9
import { GithubAuthProvider } from "firebase/auth"; const credential = GithubAuthProvider.credential(token);
웹 버전 8
var credential = firebase.auth.GithubAuthProvider.credential(token);
-
사용자 인증 정보를 사용하여 Identity Platform으로 사용자를 로그인합니다.
웹 버전 9
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; // ... });
웹 버전 8
// 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; // ... });
다음 단계
- Identity Platform 사용자에 대해 자세히 알아보세요.
- 다른 ID 공급업체로 사용자를 로그인 처리합니다.