자바스크립트에서 Apple을 통해 인증

Firebase SDK를 통해 엔드 투 엔드 OAuth 2.0 로그인 과정을 실행하여 사용자가 Apple ID를 사용해 Firebase에 인증하도록 할 수 있습니다.

시작하기 전에

사용자가 Apple 계정을 통해 로그인하도록 하려면 우선 Apple의 개발자 사이트에서 Apple로 로그인을 구성하고 Firebase 프로젝트에서 로그인 제공업체를 Apple로 사용 설정합니다.

Apple Developer Program에 가입

Apple로 로그인은 Apple Developer Program의 멤버만 구성할 수 있습니다.

Apple로 로그인 구성

Apple Developer 사이트에서 다음을 수행합니다.

  1. 웹용 Apple로 로그인 구성의 첫 번째 섹션에 설명된 대로 웹사이트를 앱에 연결합니다. 메시지가 표시되면 다음 URL을 반환 URL로 등록합니다.

    https://YOUR_FIREBASE_PROJECT_ID.firebaseapp.com/__/auth/handler

    Firebase 프로젝트 ID는 Firebase Console 설정 페이지에서 확인할 수 있습니다.

    완료했으면 새 서비스 ID를 기록해 둡니다. 이 ID는 다음 섹션에서도 필요합니다.

  2. Apple 비공개 키로 로그인을 생성합니다. 다음 섹션에서는 새로운 비공개 키와 키 ID가 필요합니다.
  3. 이메일 링크 로그인, 이메일 주소 인증, 계정 변경 취소 등 사용자에게 이메일을 보내는 Firebase 인증의 기능 중 하나라도 사용한다면 Apple에서 Firebase 인증을 통해 전송된 이메일을 익명 처리된 Apple 이메일 주소로 전달할 수 있도록 Apple 비공개 이메일 릴레이 서비스를 구성하고 noreply@YOUR_FIREBASE_PROJECT_ID.firebaseapp.com(또는 맞춤설정된 이메일 템플릿 도메인)을 등록해야 합니다.

Apple을 로그인 제공업체로 사용 설정

  1. 프로젝트에 Firebase를 추가합니다.
  2. Firebase Console에서 인증 섹션을 엽니다. 로그인 방법 탭에서 Apple 제공업체를 사용 설정합니다. 이전 섹션에서 만든 서비스 ID를 지정합니다. OAuth 코드 흐름 구성 섹션에서도 Apple 팀 ID외에 이전 섹션에서 만든 비공개 키 및 키 ID를 지정합니다.

Apple의 익명 처리된 데이터 요구사항 준수

Apple로 로그인에는 사용자가 로그인할 때 이메일 주소 등의 데이터를 익명처리할 수 있는 옵션이 제공됩니다. 이 옵션을 선택한 사용자는 privaterelay.appleid.com 도메인의 이메일 주소를 갖게 됩니다. 앱에서 Apple로 로그인을 사용하는 경우 이 익명처리된 Apple ID에 대한 Apple의 관련 개발자 정책 또는 약관을 모두 준수해야 합니다.

또한 개인 식별 정보를 익명처리된 Apple ID와 연결하려면 먼저 사용자 동의를 받아야 합니다. Firebase 인증 사용에는 다음 작업이 포함될 수 있습니다.

  • 이메일 주소와 익명처리된 Apple ID 연결
  • 전화번호와 익명처리된 Apple ID 연결
  • 익명처리되지 않은 소셜 사용자 인증 정보(Facebook, Google 등)와 익명처리된 Apple ID 연결

위 목록은 추후 변경되거나 추가될 수 있습니다. 개발자 계정의 Membership(멤버십) 섹션에서 Apple Developer Program License Agreement(Apple Developer Program 라이선스 계약)를 참조하여 앱이 Apple의 요구사항을 충족하는지 확인하세요.

Firebase SDK로 로그인 과정 처리

웹 앱을 빌드하는 경우 Firebase 자바스크립트 SDK로 전체 로그인 과정을 처리하면 가장 손쉽게 Apple 계정을 사용하여 사용자를 Firebase에 인증할 수 있습니다.

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

  1. 해당하는 제공업체 ID apple.com을 사용하여 OAuthProvider 인스턴스를 만듭니다.

    웹 모듈식 API

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

    웹 네임스페이스화된 API

    var provider = new firebase.auth.OAuthProvider('apple.com');
  2. 선택사항: 인증 제공업체에 요청하고자 하는 기본값 범위를 넘는 OAuth 2.0 범위를 추가로 지정합니다.

    웹 모듈식 API

    provider.addScope('email');
    provider.addScope('name');

    웹 네임스페이스화된 API

    provider.addScope('email');
    provider.addScope('name');

    기본적으로 이메일 주소당 계정 1개가 사용 설정되어 있으면 Firebase에서 이메일 및 이름 범위를 요청합니다. 이 설정을 이메일 주소당 여러 계정으로 변경하면 별도로 지정하지 않는 한 Firebase는 Apple에 범위를 요청하지 않습니다.

  3. 선택사항: Apple의 로그인 화면을 영어가 아닌 다른 언어로 표시하려면 locale 매개변수를 설정하세요. 지원되는 언어는 Apple로 로그인 문서를 참조하세요.

    웹 모듈식 API

    provider.setCustomParameters({
      // Localize the Apple authentication screen in French.
      locale: 'fr'
    });

    웹 네임스페이스화된 API

    provider.setCustomParameters({
      // Localize the Apple authentication screen in French.
      locale: 'fr'
    });
  4. OAuth 제공업체 객체를 사용해 Firebase에 인증합니다. 팝업 창을 띄우거나 로그인 페이지로 리디렉션하여 사용자가 Apple 계정에 로그인하도록 유도할 수 있습니다. 휴대기기의 경우 리디렉션을 사용할 것을 권장합니다.

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

      웹 모듈식 API

      import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      signInWithPopup(auth, provider)
        .then((result) => {
          // The signed-in user info.
          const user = result.user;
      
          // Apple credential
          const credential = OAuthProvider.credentialFromResult(result);
          const accessToken = credential.accessToken;
          const idToken = credential.idToken;
      
          // 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 credential that was used.
          const credential = OAuthProvider.credentialFromError(error);
      
          // ...
        });

      웹 네임스페이스화된 API

      firebase
        .auth()
        .signInWithPopup(provider)
        .then((result) => {
          /** @type {firebase.auth.OAuthCredential} */
          var credential = result.credential;
      
          // The signed-in user info.
          var user = result.user;
      
          // You can also get the Apple OAuth Access and ID Tokens.
          var accessToken = credential.accessToken;
          var idToken = credential.idToken;
      
          // IdP data available using getAdditionalUserInfo(result)
        // ...
        })
        .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를 사용할 때는 권장사항을 따르세요.

    웹 모듈식 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";
    
    // Result from Redirect auth flow.
    const auth = getAuth();
    getRedirectResult(auth)
      .then((result) => {
        const credential = OAuthProvider.credentialFromResult(result);
        if (credential) {
          // You can also get the Apple OAuth Access and ID Tokens.
          const accessToken = credential.accessToken;
          const idToken = credential.idToken;
        }
        // The signed-in user info.
        const user = result.user;
      })
      .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 credential that was used.
        const credential = OAuthProvider.credentialFromError(error);
    
        // ...
      });

    웹 네임스페이스화된 API

    // Result from Redirect auth flow.
    firebase
      .auth()
      .getRedirectResult()
      .then((result) => {
        if (result.credential) {
          /** @type {firebase.auth.OAuthCredential} */
          var credential = result.credential;
    
          // You can get the Apple OAuth Access and ID Tokens.
          var accessToken = credential.accessToken;
          var idToken = credential.idToken;
    
          // IdP data available in result.additionalUserInfo.profile.
          // ...
        }
        // The signed-in user info.
        var user = result.user;
      })
      .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 참조를 확인하세요.

    Firebase 인증에서 지원하는 다른 제공업체와 달리, Apple은 사진 URL을 제공하지 않습니다.

    또한 사용자가 자신의 이메일을 앱에 공유하지 않으면 Apple은 이 사용자의 고유 이메일 주소를 xyz@privaterelay.appleid.com 형식으로 프로비저닝하여 개발자 앱으로 공유합니다. 비공개 이메일 릴레이 서비스를 구성한 경우 Apple은 익명처리된 주소로 전송된 이메일을 사용자의 실제 이메일 주소로 전달합니다.

    Apple은 사용자가 처음 로그인할 때만 표시 이름 등의 사용자 정보만 앱에 공유합니다. 일반적으로 Firebase는 사용자가 Apple 계정으로 처음 로그인할 때 표시 이름을 저장하며, 이 표시 이름은 firebase.auth().currentUser.displayName을 사용하여 가져올 수 있습니다. 하지만 이전에 Firebase를 사용하지 않고 Apple을 사용하여 사용자를 앱에 로그인하도록 했으면 Apple은 Firebase에 사용자의 표시 이름을 제공하지 않습니다.

재인증 및 계정 연결

최근 로그인한 적이 있어야 진행할 수 있는 중요한 작업을 위해 새로운 사용자 인증 정보를 가져오는 데 사용할 수 있는 reauthenticateWithPopup()reauthenticateWithRedirect()에서도 동일한 패턴을 사용할 수 있습니다.

웹 모듈식 API

import { getAuth, reauthenticateWithPopup, OAuthProvider } from "firebase/auth";

// Result from Redirect auth flow.
const auth = getAuth();
const provider = new OAuthProvider('apple.com');

reauthenticateWithPopup(auth.currentUser, provider)
  .then((result) => {
    // User is re-authenticated with fresh tokens minted and can perform
    // sensitive operations like account deletion, or updating their email
    // address or password.

    // The signed-in user info.
    const user = result.user;

    // You can also get the Apple OAuth Access and ID Tokens.
    const credential = OAuthProvider.credentialFromResult(result);
    const accessToken = credential.accessToken;
    const idToken = credential.idToken;

    // ...
  })
  .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 credential that was used.
    const credential = OAuthProvider.credentialFromError(error);

    // ...
  });

웹 네임스페이스화된 API

const provider = new firebase.auth.OAuthProvider('apple.com');

firebase
  .auth()
  .currentUser
  .reauthenticateWithPopup(provider)
  .then((result) => {
    // User is re-authenticated with fresh tokens minted and can perform
    // sensitive operations like account deletion, or updating their email
    // address or password.
    /** @type {firebase.auth.OAuthCredential} */
    var credential = result.credential;

    // The signed-in user info.
    var user = result.user;
     // You can also get the Apple OAuth Access and ID Tokens.
    var accessToken = credential.accessToken;
    var idToken = credential.idToken;

    // 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;

    // ...
  });

또한 linkWithPopup()linkWithRedirect()를 사용하여 여러 ID 공급업체를 기존 계정에 연결할 수 있습니다.

Apple에서는 개발자가 사용자의 Apple 계정을 다른 데이터에 연결하기 전에 사용자에게 명시적인 동의를 얻도록 요구하고 있습니다.

예를 들어 Facebook 계정을 현재 Firebase 계정에 연결하려면 사용자가 Facebook에 로그인할 때 얻은 액세스 토큰을 사용하세요.

웹 모듈식 API

import { getAuth, linkWithPopup, FacebookAuthProvider } from "firebase/auth";

const auth = getAuth();
const provider = new FacebookAuthProvider();
provider.addScope('user_birthday');

// Assuming the current user is an Apple user linking a Facebook provider.
linkWithPopup(auth.currentUser, provider)
    .then((result) => {
      // Facebook credential is linked to the current Apple user.
      // ...

      // The user can now sign in to the same account
      // with either Apple or Facebook.
    })
    .catch((error) => {
      // Handle error.
    });

웹 네임스페이스화된 API

const provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('user_birthday');

// Assuming the current user is an Apple user linking a Facebook provider.
firebase.auth().currentUser.linkWithPopup(provider)
    .then((result) => {
      // Facebook credential is linked to the current Apple user.
      // Facebook additional data available in result.additionalUserInfo.profile,

      // Additional Facebook OAuth access token can also be retrieved.
      // result.credential.accessToken

      // The user can now sign in to the same account
      // with either Apple or Facebook.
    })
    .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 허용 목록에 추가되었는지 확인합니다.

기본 firebaseapp.com 도메인과 마찬가지로 커스텀 도메인을 Apple에 인증해야 합니다.

http://auth.custom.example.com/.well-known/apple-developer-domain-association.txt

고급: Node.js에서 Firebase에 인증

Node.js 애플리케이션에서 Firebase에 인증하는 방법은 다음과 같습니다.

  1. Apple 계정으로 사용자를 로그인 처리하고 사용자의 Apple ID 토큰을 가져옵니다. 여러 방식으로 이 작업을 수행할 수 있습니다. 예를 들어 Node.js 앱에 브라우저 프런트엔드가 있으면 다음을 수행합니다.

    1. 백엔드에서 임의 문자열('nonce')을 생성하고 SHA256 해시를 계산합니다. nonce는 백엔드와 Apple의 인증 서버를 1회 왕복하는 과정을 검증하는 데 사용하는 일회용 값입니다.

      웹 모듈식 API

      const crypto = require("crypto");
      const string_decoder = require("string_decoder");
      
      // Generate a new random string for each sign-in
      const generateNonce = (length) => {
        const decoder = new string_decoder.StringDecoder("ascii");
        const buf = Buffer.alloc(length);
        let nonce = "";
        while (nonce.length < length) {
          crypto.randomFillSync(buf);
          nonce = decoder.write(buf);
        }
        return nonce.slice(0, length);
      };
      
      const unhashedNonce = generateNonce(10);
      
      // SHA256-hashed nonce in hex
      const hashedNonceHex = crypto.createHash('sha256')
        .update(unhashedNonce).digest().toString('hex');

      웹 네임스페이스화된 API

      const crypto = require("crypto");
      const string_decoder = require("string_decoder");
      
      // Generate a new random string for each sign-in
      const generateNonce = function(length) {
        const decoder = new string_decoder.StringDecoder("ascii");
        const buf = Buffer.alloc(length);
        var nonce = "";
        while (nonce.length < length) {
          crypto.randomFillSync(buf);
          nonce = decoder.write(buf);
        }
        return nonce.slice(0, length);
      };
      
      const unhashedNonce = generateNonce(10);
      
      // SHA256-hashed nonce in hex
      const hashedNonceHex = crypto.createHash('sha256')
        .update(unhashedNonce).digest().toString('hex');
    2. 로그인 페이지의 Apple로 로그인 구성에서 해시된 nonce를 지정합니다.

      <script src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"></script>
      <div id="appleid-signin" data-color="black" data-border="true" data-type="sign in"></div>
      <script>
          AppleID.auth.init({
              clientId: YOUR_APPLE_CLIENT_ID,
              scope: 'name email',
              redirectURI: URL_TO_YOUR_REDIRECT_HANDLER,  // See the next step.
              state: '[STATE]',  // Optional value that Apple will send back to you
                                 // so you can return users to the same context after
                                 // they sign in.
              nonce: HASHED_NONCE  // The hashed nonce you generated in the previous step.
          });
      </script>
      
    3. POST된 인증 응답 서버 측에서 Apple ID 토큰을 가져옵니다.

      app.post('/redirect', (req, res) => {
        const savedState = req.cookies.__session;
        const code = req.body.code;
        const state = req.body.state;
        const appleIdToken = req.body.id_token;
        if (savedState !== state || !code) {
          res.status(403).send('403: Permission denied');
        } else {
          // Sign in with Firebase using appleIdToken. (See next step).
        }
      });
      

    Configuring Your Webpage for Sign In with Apple(Apple로 로그인을 위한 웹페이지 구성)도 참조하세요.

  2. 사용자의 Apple ID 토큰을 가져온 후 해당 토큰으로 사용자 인증 정보 객체를 만들고 이 객체로 사용자를 로그인 처리합니다.

    웹 모듈식 API

    import { getAuth, signInWithCredential, OAuthProvider } from "firebase/auth";
    
    const auth = getAuth();
    
    // Build Firebase credential with the Apple ID token.
    const provider = new OAuthProvider('apple.com');
    const authCredential = provider.credential({
      idToken: appleIdToken,
      rawNonce: unhashedNonce,
    });
    
    // Sign in with credential form the Apple user.
    signInWithCredential(auth, authCredential)
      .then((result) => {
        // User signed in.
      })
      .catch((error) => {
        // An error occurred. If error.code == 'auth/missing-or-invalid-nonce',
        // make sure you're sending the SHA256-hashed nonce as a hex string
        // with your request to Apple.
        console.log(error);
      });

    웹 네임스페이스화된 API

    // Build Firebase credential with the Apple ID token.
    const provider = new firebase.auth.OAuthProvider('apple.com');
    const authCredential = provider.credential({
      idToken: appleIdToken,
      rawNonce: unhashedNonce,
    });
    
    // Sign in with credential form the Apple user.
    firebase.auth().signInWithCredential(authCredential)
      .then((result) => {
        // User signed in.
      })
      .catch((error) => {
        // An error occurred. If error.code == 'auth/missing-or-invalid-nonce',
        // make sure you're sending the SHA256-hashed nonce as a hex string
        // with your request to Apple.
        console.log(error);
      });

다음 단계

사용자가 처음으로 로그인하면 신규 사용자 계정이 생성되고 사용자가 로그인할 때 사용한 사용자 인증 정보(사용자 이름과 비밀번호, 전화번호 또는 인증 제공업체 정보)에 연결됩니다. 이 신규 계정은 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.
});