Twitter로 사용자 로그인
이 문서에서는 Identity Platform을 사용하여 트위터로 사용자를 로그인하는 방법을 보여줍니다.
시작하기 전에
이 튜토리얼에서는 Identity Platform을 이미 사용 설정했으며 HTML 및 자바스크립트를 사용하여 작성된 기본 웹 앱이 있다고 가정합니다. Identity Platform을 사용 설정하고 로그인하는 방법을 알아보려면 빠른 시작을 참고하세요.
Twitter를 공급업체로 구성
GitHub를 ID 공급업체로 구성하려면 다음 안내를 따르세요.
- Google Cloud 콘솔에서 ID 공급업체 페이지로 이동합니다.
- 공급업체 추가를 클릭합니다.
- 목록에서 트위터를 선택합니다.
- Twitter 앱 ID와 앱 보안 비밀을 입력합니다. 아직 ID와 보안 비밀이 없으면 Twitter 앱 페이지에서 가져올 수 있습니다.
-
트위터 구성 아래에 나열된 URI를 트위터 앱의 유효한 OAuth 리디렉션 URI로 구성합니다. Identity Platform에서 커스텀 도메인을 구성한 경우 기본 도메인 대신 커스텀 도메인을 사용하도록 트위터 앱 구성의 리디렉션 URI를 업데이트합니다. 예를 들어
https://myproject.firebaseapp.com/__/auth/handler
를https://auth.myownpersonaldomain.com/__/auth/handler
로 변경합니다. -
프로젝트 설정 측면 창에서 도메인 추가를 클릭하고 앱의 도메인을 추가합니다.
프로덕션 프로젝트에는
localhost
를 포함하지 않는 것이 좋습니다. - 애플리케이션 구성 섹션에서 설정 세부정보를 클릭합니다. 스니펫을 앱 코드에 복사하여 Identity Platform 클라이언트 SDK를 초기화합니다.
- 저장을 클릭합니다.
클라이언트 SDK로 사용자 로그인
-
다음와 같이 Twitter 제공업체 객체의 인스턴스를 생성합니다.
웹 버전 9
import { TwitterAuthProvider } from "firebase/auth"; const provider = new TwitterAuthProvider();
웹 버전 8
var provider = new firebase.auth.TwitterAuthProvider();
-
선택사항: 인증 흐름을 현지화합니다. 언어를 지정하거나 기기의 기본 언어를 사용할 수 있습니다.
웹 버전 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 매개변수를 지정합니다. 이는 트위터에만 해당하며 일반적으로 인증 환경을 맞춤설정하는 데 사용됩니다. OAuth 또는 Identity Platform에서 예약한 매개변수는 전달할 수 없습니다.
웹 버전 9
provider.setCustomParameters({ 'lang': 'es' });
웹 버전 8
provider.setCustomParameters({ 'lang': 'es' });
-
트위터 공급업체 객체를 사용하여 사용자를 로그인합니다. 팝업 창을 열거나 현재 페이지를 리디렉션할 수 있습니다. 휴대기기에서는 사용자가 리디렉션하기 더 용이합니다.
signInWithPopup()
을 호출하면 팝업이 나타납니다.웹 버전 9
import { getAuth, signInWithPopup, TwitterAuthProvider } from "firebase/auth"; const auth = getAuth(); signInWithPopup(auth, provider) .then((result) => { // This gives you a the Twitter OAuth 1.0 Access Token and Secret. // You can use these server side with your app's credentials to access the Twitter API. const credential = TwitterAuthProvider.credentialFromResult(result); const token = credential.accessToken; const secret = credential.secret; // 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 = TwitterAuthProvider.credentialFromError(error); // ... });
웹 버전 8
firebase .auth() .signInWithPopup(provider) .then((result) => { /** @type {firebase.auth.OAuthCredential} */ var credential = result.credential; // This gives you a the Twitter OAuth 1.0 Access Token and Secret. // You can use these server side with your app's credentials to access the Twitter API. var token = credential.accessToken; var secret = credential.secret; // 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()
를 호출하여 트위터 토큰을 검색합니다.웹 버전 9
import { getAuth, getRedirectResult, TwitterAuthProvider } from "firebase/auth"; const auth = getAuth(); getRedirectResult(auth) .then((result) => { // This gives you a the Twitter OAuth 1.0 Access Token and Secret. // You can use these server side with your app's credentials to access the Twitter API. const credential = TwitterAuthProvider.credentialFromResult(result); const token = credential.accessToken; const secret = credential.secret; // ... // 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 = TwitterAuthProvider.credentialFromError(error); // ... });
웹 버전 8
firebase.auth() .getRedirectResult() .then((result) => { if (result.credential) { /** @type {firebase.auth.OAuthCredential} */ var credential = result.credential; // This gives you a the Twitter OAuth 1.0 Access Token and Secret. // You can use these server side with your app's credentials to access the Twitter API. var token = credential.accessToken; var secret = credential.secret; // ... } // 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; // ... });
액세스 토큰이 있으면 이를 사용하여 트위터 API를 호출할 수 있습니다. 예를 들면 다음과 같습니다.
REST
curl --request POST --url 'https://api.twitter.com/1.1/statuses/update.json?status=Hello%20world' --header 'authorization: OAuth oauth_consumer_key="CONSUMER_API_KEY", oauth_nonce="OAUTH_NONCE", oauth_signature="OAUTH_SIGNATURE", oauth_signature_method="HMAC-SHA1", oauth_timestamp="OAUTH_TIMESTAMP", oauth_token="ACCESS_TOKEN", oauth_version="1.0"'
수동으로 사용자 로그인
클라이언트 SDK를 사용하지 않으려면 로그인 과정을 수동으로 처리할 수도 있습니다.
- 개발자 문서의 단계에 따라 트위터 인증을 앱에 통합합니다.
- 이전 단계에서 구현한 흐름을 사용하여 트위터로 사용자를 로그인합니다.
-
트위터에서 수신한 토큰을 Identity Platform 사용자 인증 정보로 교환합니다.
웹 버전 9
import { TwitterAuthProvider } from "firebase/auth"; const credential = TwitterAuthProvider.credential(accessToken, secret);
웹 버전 8
var credential = firebase.auth.TwitterAuthProvider.credential(accessToken, secret);
-
사용자 인증 정보를 사용하여 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 공급업체로 사용자를 로그인 처리합니다.