ตรวจสอบสิทธิ์โดยใช้ GitHub ด้วย JavaScript

คุณสามารถอนุญาตให้ผู้ใช้ตรวจสอบสิทธิ์กับ Firebase โดยใช้บัญชี GitHub โดยผสานรวมการตรวจสอบสิทธิ์ GitHub เข้ากับแอปของคุณ คุณสามารถผสานรวมการตรวจสอบสิทธิ์ GitHub โดยใช้ Firebase SDK เพื่อดำเนินการตามขั้นตอนการลงชื่อเข้าใช้ หรือดำเนินการตามขั้นตอนการลงชื่อเข้าใช้ GitHub OAuth 2.0 ด้วยตนเอง แล้วส่งโทเค็นการเข้าถึงที่ได้ไปยัง Firebase

ก่อนเริ่มต้น

  1. เพิ่ม Firebase ลงในโปรเจ็กต์ JavaScript
  2. เปิดส่วน Auth ในคอนโซล Firebase
  3. ในแท็บวิธีการลงชื่อเข้าใช้ ให้เปิดใช้ผู้ให้บริการ GitHub
  4. เพิ่มรหัสไคลเอ็นต์และรหัสลับไคลเอ็นต์จากคอนโซลของนักพัฒนาซอฟต์แวร์ของผู้ให้บริการนั้นลงในการกำหนดค่าผู้ให้บริการ ดังนี้
    1. ลงทะเบียนแอปเป็นแอปพลิเคชันของนักพัฒนาแอปใน GitHub และรับรหัสไคลเอ็นต์และรหัสลับไคลเอ็นต์ OAuth 2.0 ของแอป
    2. ตรวจสอบว่าได้ตั้งค่า URI การเปลี่ยนเส้นทาง OAuth ของ Firebase (เช่น my-app-12345.firebaseapp.com/__/auth/handler) เป็น URL เรียกกลับการให้สิทธิ์ในหน้าการตั้งค่าของแอปในการกำหนดค่าแอป GitHub
  5. คลิกบันทึก

จัดการขั้นตอนการลงชื่อเข้าใช้ด้วย Firebase SDK

หากคุณกำลังสร้างเว็บแอป วิธีที่ง่ายที่สุดในการตรวจสอบสิทธิ์ผู้ใช้ด้วย Firebase โดยใช้บัญชี GitHub ของผู้ใช้คือจัดการขั้นตอนการลงชื่อเข้าใช้ด้วย Firebase JavaScript SDK (หากต้องการตรวจสอบสิทธิ์ผู้ใช้ใน Node.js หรือสภาพแวดล้อมอื่นๆ ที่ไม่ใช่เบราว์เซอร์ คุณต้องจัดการขั้นตอนการลงชื่อเข้าใช้ด้วยตนเอง)

หากต้องการจัดการขั้นตอนการลงชื่อเข้าใช้ด้วย Firebase JavaScript 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 หากต้องการเพิ่มพารามิเตอร์ที่กําหนดเอง ให้เรียกใช้ setCustomParameters ในผู้ให้บริการที่เริ่มต้นด้วยออบเจ็กต์ที่มีคีย์ตามที่ระบุไว้ในเอกสารประกอบของผู้ให้บริการ OAuth และค่าที่เกี่ยวข้อง เช่น
    WebWeb
    provider.setCustomParameters({
      'allow_signup': 'false'
    });
    provider.setCustomParameters({
      'allow_signup': 'false'
    });
    ระบบจะไม่อนุญาตให้ใช้พารามิเตอร์ OAuth ที่จําเป็นซึ่งสงวนไว้และจะละเว้น ดูรายละเอียดเพิ่มเติมได้ที่ ข้อมูลอ้างอิงเกี่ยวกับผู้ให้บริการตรวจสอบสิทธิ์
  4. ตรวจสอบสิทธิ์กับ Firebase โดยใช้ออบเจ็กต์ผู้ให้บริการ GitHub คุณสามารถแจ้งให้ผู้ใช้ลงชื่อเข้าใช้ด้วยบัญชี 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;
          // ...
        });
      นอกจากนี้ โปรดทราบว่าคุณสามารถดึงข้อมูลโทเค็น OAuth ของผู้ให้บริการ GitHub ซึ่งสามารถใช้เพื่อดึงข้อมูลเพิ่มเติมโดยใช้ GitHub API

      นอกจากนี้ คุณยังจับและจัดการข้อผิดพลาดได้ที่นี่ ดูรายการรหัสข้อผิดพลาดได้ที่เอกสารอ้างอิงเกี่ยวกับการให้สิทธิ์

    • หากต้องการลงชื่อเข้าใช้โดยเปลี่ยนเส้นทางไปยังหน้าลงชื่อเข้าใช้ ให้เรียกใช้ signInWithRedirect ดังนี้ ทําตามแนวทางปฏิบัติแนะนําเมื่อใช้ `signInWithRedirect`
      WebWeb
      import { getAuth, signInWithRedirect } from "firebase/auth";
      
      const auth = getAuth();
      signInWithRedirect(auth, provider);
      firebase.auth().signInWithRedirect(provider);
      จากนั้นเรียกโทเค็น OAuth ของผู้ให้บริการ GitHub ได้โดยเรียกใช้ getRedirectResult เมื่อหน้าเว็บโหลด
      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;
          // ...
        });
      นอกจากนี้ คุณยังจับและจัดการข้อผิดพลาดได้ที่นี่ ดูรายการรหัสข้อผิดพลาดได้ที่เอกสารอ้างอิงเกี่ยวกับการให้สิทธิ์

หากคุณเปิดใช้การตั้งค่าบัญชี 1 บัญชีต่ออีเมล 1 รายการในคอนโซล Firebase เมื่อผู้ใช้พยายามลงชื่อเข้าใช้ผู้ให้บริการ (เช่น GitHub) ด้วยอีเมลที่มีอยู่แล้วสำหรับผู้ให้บริการของผู้ใช้ Firebase รายอื่น (เช่น Google) ระบบจะแสดงข้อผิดพลาด auth/account-exists-with-different-credential พร้อมกับออบเจ็กต์ AuthCredential (โทเค็นการเข้าถึง GitHub) หากต้องการลงชื่อเข้าใช้ผู้ให้บริการที่ต้องการให้เสร็จสมบูรณ์ ผู้ใช้ต้องลงชื่อเข้าใช้ผู้ให้บริการที่มีอยู่ (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) {
  // ...
}

โหมดเปลี่ยนเส้นทาง

ข้อผิดพลาดนี้จะได้รับการจัดการในลักษณะที่คล้ายกันในโหมดการเปลี่ยนเส้นทาง โดยมีความแตกต่างตรงที่ต้องแคชข้อมูลเข้าสู่ระบบที่รอดำเนินการระหว่างการเปลี่ยนเส้นทางหน้าเว็บ (เช่น โดยใช้พื้นที่เก็บข้อมูลเซสชัน)

จัดการขั้นตอนการลงชื่อเข้าใช้ด้วยตนเอง

นอกจากนี้ คุณยังตรวจสอบสิทธิ์กับ Firebase โดยใช้บัญชี GitHub ได้ด้วย โดยจัดการขั้นตอนการลงชื่อเข้าใช้ด้วยการเรียกใช้ปลายทาง OAuth 2.0 ของ GitHub ดังนี้

  1. ผสานรวมการตรวจสอบสิทธิ์ของ GitHub เข้ากับแอปโดยทําตาม เอกสารประกอบสําหรับนักพัฒนาซอฟต์แวร์ เมื่อสิ้นสุดขั้นตอนการลงชื่อเข้าใช้ GitHub คุณจะได้รับโทเค็นการเข้าถึง OAuth 2.0
  2. หากต้องการลงชื่อเข้าใช้แอปพลิเคชัน Node.js ให้ส่งโทเค็นการเข้าถึง OAuth ไปยังแอปพลิเคชัน Node.js
  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;
        // ...
      });

ตรวจสอบสิทธิ์ด้วย Firebase ในส่วนขยาย Chrome

หากคุณกำลังสร้างแอปส่วนขยาย Chrome โปรดดู คำแนะนำเกี่ยวกับเอกสารที่อยู่นอกหน้าจอ

เมื่อสร้างโปรเจ็กต์ Firebase จะจัดสรรโดเมนย่อยที่ไม่ซ้ำกันให้กับโปรเจ็กต์ ดังนี้ https://my-app-12345.firebaseapp.com

ซึ่งจะใช้เป็นกลไกการเปลี่ยนเส้นทางสำหรับการลงชื่อเข้าใช้ OAuth ด้วย โดเมนดังกล่าวจะต้องได้รับอนุญาตให้ใช้กับผู้ให้บริการ OAuth ทั้งหมดที่รองรับ อย่างไรก็ตาม การดำเนินการนี้หมายความว่าผู้ใช้อาจเห็นโดเมนดังกล่าวขณะลงชื่อเข้าใช้ GitHub ก่อนที่จะเปลี่ยนเส้นทางกลับไปที่แอปพลิเคชัน ต่อไปที่: https://my-app-12345.firebaseapp.com

หากไม่ต้องการให้ระบบแสดงโดเมนย่อย คุณสามารถตั้งค่าโดเมนที่กำหนดเองกับ Firebase Hosting ได้โดยทำดังนี้

  1. ทำตามขั้นตอนที่ 1-3 ในหัวข้อตั้งค่าโดเมนสำหรับ Hosting เมื่อคุณยืนยันการเป็นเจ้าของโดเมน Hosting จะจัดสรรใบรับรอง SSL สำหรับโดเมนที่กำหนดเอง
  2. เพิ่มโดเมนที่กำหนดเองลงในรายการโดเมนที่ได้รับอนุญาตในคอนโซล Firebase: auth.custom.domain.com
  3. ในคอนโซลนักพัฒนาซอฟต์แวร์ของ GitHub หรือหน้าการตั้งค่า OAuth ให้เพิ่ม URL ของหน้าการเปลี่ยนเส้นทางในรายการที่อนุญาต ซึ่งจะเข้าถึงได้ในโดเมนที่กำหนดเอง https://auth.custom.domain.com/__/auth/handler
  4. เมื่อเริ่มต้นใช้งานไลบรารี JavaScript ให้ระบุโดเมนที่กำหนดเองด้วยช่อง 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 Database และ Cloud Storage กฎความปลอดภัย คุณสามารถรับรหัสผู้ใช้ที่ไม่ซ้ำของผู้ใช้ที่ลงชื่อเข้าใช้จากตัวแปร auth และนำไปใช้ควบคุมข้อมูลที่ผู้ใช้เข้าถึงได้

คุณสามารถอนุญาตให้ผู้ใช้ลงชื่อเข้าใช้แอปโดยใช้ผู้ให้บริการตรวจสอบสิทธิ์หลายรายได้โดยการลิงก์ข้อมูลเข้าสู่ระบบของผู้ให้บริการตรวจสอบสิทธิ์กับบัญชีผู้ใช้ที่มีอยู่

หากต้องการออกจากระบบของผู้ใช้ ให้เรียกใช้ 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.
});