Dễ dàng thêm đăng nhập vào ứng dụng Web của bạn với FirebaseUI

FirebaseUI là một thư viện được xây dựng dựa trên SDK xác thực Firebase, cung cấp các luồng giao diện người dùng thả vào để sử dụng trong ứng dụng của bạn. FirebaseUI cung cấp các lợi ích sau:

  • Nhiều nhà cung cấp - quy trình đăng nhập cho email / mật khẩu, liên kết email, xác thực điện thoại, đăng nhập Google, Facebook, Twitter và GitHub.
  • Liên kết tài khoản - quy trình liên kết an toàn các tài khoản người dùng giữa các nhà cung cấp danh tính.
  • Tùy chỉnh - ghi đè các kiểu CSS của FirebaseUI để phù hợp với yêu cầu ứng dụng của bạn. Ngoài ra, vì FirebaseUI là mã nguồn mở, bạn có thể phân nhánh dự án và tùy chỉnh chính xác theo nhu cầu của mình.
  • Đăng ký một chạm và đăng nhập tự động - tích hợp tự động với Đăng ký một chạm để đăng nhập nhanh trên nhiều thiết bị.
  • Giao diện người dùng được bản địa hóa - quốc tế hóa cho hơn 40 ngôn ngữ .
  • Nâng cấp người dùng ẩn danh - khả năng nâng cấp người dùng ẩn danh thông qua đăng nhập / đăng ký. Để biết thêm thông tin, hãy truy cập phần Nâng cấp người dùng ẩn danh .

Trước khi bắt đầu

  1. Thêm Xác thực Firebase vào ứng dụng web của bạn , đảm bảo bạn đang sử dụng SDK phiên bản v9 (được khuyến nghị) hoặc cũ hơn (xem thanh bên ở trên).

  2. Bao gồm FirebaseUI thông qua một trong các tùy chọn sau:

    1. CDN

      Bao gồm tập lệnh và tệp CSS sau trong thẻ <head> của trang của bạn, bên dưới đoạn mã khởi tạo từ Bảng điều khiển Firebase:

      <script src="https://www.gstatic.com/firebasejs/ui/6.0.1/firebase-ui-auth.js"></script>
      <link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/6.0.1/firebase-ui-auth.css" />
      
    2. Mô-đun npm

      Cài đặt FirebaseUI và các phụ thuộc của nó qua npm bằng lệnh sau:

      $ npm install firebaseui --save
      

      require các mô-đun sau trong tệp nguồn của bạn:

      var firebase = require('firebase');
      var firebaseui = require('firebaseui');
      
    3. Thành phần Bower

      Cài đặt FirebaseUI và các phụ thuộc của nó qua Bower bằng lệnh sau:

      $ bower install firebaseui --save
      

      Bao gồm các tệp được yêu cầu trong HTML của bạn, nếu Máy chủ HTTP của bạn phân phát các tệp trong bower_components/ :

      <script src="bower_components/firebaseui/dist/firebaseui.js"></script>
      <link type="text/css" rel="stylesheet" href="bower_components/firebaseui/dist/firebaseui.css" />
      

Khởi tạo FirebaseUI

Sau khi nhập SDK, hãy khởi chạy giao diện người dùng Auth.

// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());

Thiết lập phương thức đăng nhập

Trước khi có thể sử dụng Firebase để đăng nhập người dùng, bạn phải bật và định cấu hình các phương thức đăng nhập mà bạn muốn hỗ trợ.

Địa chỉ email và mật khẩu

  1. Trong bảng điều khiển Firebase , mở phần Xác thực và bật xác thực email và mật khẩu.

  2. Thêm ID nhà cung cấp email vào danh sách FirebaseUI signInOptions .

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        firebase.auth.EmailAuthProvider.PROVIDER_ID
      ],
      // Other config options...
    });
    
  3. Tùy chọn : EmailAuthProvider có thể được định cấu hình để yêu cầu người dùng nhập tên hiển thị (mặc định là true ).

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        {
          provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
          requireDisplayName: false
        }
      ]
    });
    
  1. Trong bảng điều khiển Firebase , hãy mở phần Xác thực . Trên tab Phương pháp đăng nhập , hãy bật nhà cung cấp Email / Mật khẩu . Lưu ý rằng đăng nhập email / mật khẩu phải được bật để sử dụng đăng nhập liên kết email.

  2. Trong cùng phần này, hãy bật phương pháp đăng nhập liên kết Email (đăng nhập không cần mật khẩu) và nhấp vào Lưu .

  3. Thêm ID nhà cung cấp email vào danh sách FirebaseUI signInOptions cùng với liên kết email signInMethod .

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        {
          provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
          signInMethod: firebase.auth.EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD
        }
      ],
      // Other config options...
    });
    
  4. Khi hiển thị giao diện người dùng đăng nhập có điều kiện (liên quan đến các ứng dụng trang đơn), hãy sử dụng ui.isPendingRedirect() để phát hiện xem URL có tương ứng với đăng nhập bằng liên kết email hay không và giao diện người dùng cần được hiển thị để hoàn tất đăng nhập.

    // Is there an email link sign-in?
    if (ui.isPendingRedirect()) {
      ui.start('#firebaseui-auth-container', uiConfig);
    }
    // This can also be done via:
    if (firebase.auth().isSignInWithEmailLink(window.location.href)) {
      ui.start('#firebaseui-auth-container', uiConfig);
    }
    
  5. Tùy chọn : Có thể định cấu hình EmailAuthProvider cho đăng nhập liên kết email để cho phép hoặc chặn người dùng hoàn tất đăng nhập trên nhiều thiết bị.

    Một lệnh gọi lại emailLinkSignIn tùy chọn có thể được xác định để trả về cấu hình firebase.auth.ActionCodeSettings để sử dụng khi gửi liên kết. Điều này cung cấp khả năng chỉ định cách liên kết có thể được xử lý, liên kết động tùy chỉnh, trạng thái bổ sung trong liên kết sâu, v.v. Khi không được cung cấp, URL hiện tại sẽ được sử dụng và luồng chỉ web được kích hoạt.

    Đăng nhập liên kết email trong FirebaseUI-web tương thích với FirebaseUI-AndroidFirebaseUI-iOS trong đó một người dùng bắt đầu quy trình từ FirebaseUI-Android có thể mở liên kết và hoàn tất đăng nhập bằng FirebaseUI-web. Điều này cũng đúng với luồng ngược lại.

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        {
          provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
          signInMethod: firebase.auth.EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD,
          // Allow the user the ability to complete sign-in cross device,
          // including the mobile apps specified in the ActionCodeSettings
          // object below.
          forceSameDevice: false,
          // Used to define the optional firebase.auth.ActionCodeSettings if
          // additional state needs to be passed along request and whether to open
          // the link in a mobile app if it is installed.
          emailLinkSignIn: function() {
            return {
              // Additional state showPromo=1234 can be retrieved from URL on
              // sign-in completion in signInSuccess callback by checking
              // window.location.href.
              url: 'https://www.example.com/completeSignIn?showPromo=1234',
              // Custom FDL domain.
              dynamicLinkDomain: 'example.page.link',
              // Always true for email link sign-in.
              handleCodeInApp: true,
              // Whether to handle link in iOS app if installed.
              iOS: {
                bundleId: 'com.example.ios'
              },
              // Whether to handle link in Android app if opened in an Android
              // device.
              android: {
                packageName: 'com.example.android',
                installApp: true,
                minimumVersion: '12'
              }
            };
          }
        }
      ]
    });
    

Nhà cung cấp OAuth (Google, Facebook, Twitter và GitHub)

  1. Trong bảng điều khiển Firebase , mở phần Xác thực và bật đăng nhập nhà cung cấp OAuth được chỉ định. Đảm bảo rằng ID ứng dụng khách OAuth tương ứng và bí mật cũng được chỉ định.

  2. Cũng trong phần Xác thực , hãy đảm bảo rằng miền nơi trang đăng nhập của bạn sẽ được hiển thị cũng được thêm vào danh sách miền được ủy quyền.

  3. Thêm ID nhà cung cấp OAuth vào danh sách FirebaseUI signInOptions .

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        // List of OAuth providers supported.
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        firebase.auth.FacebookAuthProvider.PROVIDER_ID,
        firebase.auth.TwitterAuthProvider.PROVIDER_ID,
        firebase.auth.GithubAuthProvider.PROVIDER_ID
      ],
      // Other config options...
    });
    
  4. Tùy chọn : Để chỉ định phạm vi tùy chỉnh hoặc thông số OAuth tùy chỉnh cho mỗi nhà cung cấp, bạn có thể chuyển một đối tượng thay vì chỉ giá trị nhà cung cấp:

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        {
          provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID,
          scopes: [
            'https://www.googleapis.com/auth/contacts.readonly'
          ],
          customParameters: {
            // Forces account selection even when one account
            // is available.
            prompt: 'select_account'
          }
        },
        {
          provider: firebase.auth.FacebookAuthProvider.PROVIDER_ID,
          scopes: [
            'public_profile',
            'email',
            'user_likes',
            'user_friends'
          ],
          customParameters: {
            // Forces password re-entry.
            auth_type: 'reauthenticate'
          }
        },
        firebase.auth.TwitterAuthProvider.PROVIDER_ID, // Twitter does not support scopes.
        firebase.auth.EmailAuthProvider.PROVIDER_ID // Other providers don't need to be given as object.
      ]
    });
    

Số điện thoại

  1. Trong bảng điều khiển Firebase , mở phần Xác thực và bật đăng nhập bằng số điện thoại.

  2. Đảm bảo rằng miền nơi trang đăng nhập của bạn sẽ được hiển thị cũng được thêm vào danh sách miền được ủy quyền.

  3. Thêm ID nhà cung cấp số điện thoại vào danh sách FirebaseUI signInOptions .

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        firebase.auth.PhoneAuthProvider.PROVIDER_ID
      ],
      // Other config options...
    });
    
  4. Tùy chọn : PhoneAuthProvider có thể được định cấu hình với các thông số reCAPTCHA tùy chỉnh cho dù reCAPTCHA hiển thị hay không nhìn thấy (mặc định là bình thường). Tham khảo tài liệu API reCAPTCHA để biết thêm chi tiết.

    Quốc gia mặc định để chọn trong phần nhập số điện thoại cũng có thể được đặt. Tham khảo danh sách mã quốc gia được hỗ trợ để biết danh sách đầy đủ các mã. Nếu không được chỉ định, đầu vào số điện thoại sẽ mặc định là Hoa Kỳ (+1).

    Các tùy chọn sau hiện đang được hỗ trợ.

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        {
          provider: firebase.auth.PhoneAuthProvider.PROVIDER_ID,
          recaptchaParameters: {
            type: 'image', // 'audio'
            size: 'normal', // 'invisible' or 'compact'
            badge: 'bottomleft' //' bottomright' or 'inline' applies to invisible.
          },
          defaultCountry: 'GB', // Set default country to the United Kingdom (+44).
          // For prefilling the national number, set defaultNationNumber.
          // This will only be observed if only phone Auth provider is used since
          // for multiple providers, the NASCAR screen will always render first
          // with a 'sign in with phone number' button.
          defaultNationalNumber: '1234567890',
          // You can also pass the full phone number string instead of the
          // 'defaultCountry' and 'defaultNationalNumber'. However, in this case,
          // the first country ID that matches the country code will be used to
          // populate the country selector. So for countries that share the same
          // country code, the selected country may not be the expected one.
          // In that case, pass the 'defaultCountry' instead to ensure the exact
          // country is selected. The 'defaultCountry' and 'defaultNationaNumber'
          // will always have higher priority than 'loginHint' which will be ignored
          // in their favor. In this case, the default country will be 'GB' even
          // though 'loginHint' specified the country code as '+1'.
          loginHint: '+11234567890'
        }
      ]
    });
    

Đăng nhập

Để bắt đầu luồng đăng nhập FirebaseUI, hãy khởi tạo phiên bản FirebaseUI bằng cách chuyển phiên bản Auth bên dưới.

// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());

Xác định phần tử HTML nơi tiện ích con đăng nhập FirebaseUI sẽ được hiển thị.

<!-- The surrounding HTML is left untouched by FirebaseUI.
     Your app may use that space for branding, controls and other customizations.-->
<h1>Welcome to My Awesome App</h1>
<div id="firebaseui-auth-container"></div>
<div id="loader">Loading...</div>

Chỉ định cấu hình FirebaseUI (các nhà cung cấp được hỗ trợ và các tùy chỉnh giao diện người dùng cũng như các lệnh gọi lại thành công, v.v.).

var uiConfig = {
  callbacks: {
    signInSuccessWithAuthResult: function(authResult, redirectUrl) {
      // User successfully signed in.
      // Return type determines whether we continue the redirect automatically
      // or whether we leave that to developer to handle.
      return true;
    },
    uiShown: function() {
      // The widget is rendered.
      // Hide the loader.
      document.getElementById('loader').style.display = 'none';
    }
  },
  // Will use popup for IDP Providers sign-in flow instead of the default, redirect.
  signInFlow: 'popup',
  signInSuccessUrl: '<url-to-redirect-to-on-success>',
  signInOptions: [
    // Leave the lines as is for the providers you want to offer your users.
    firebase.auth.GoogleAuthProvider.PROVIDER_ID,
    firebase.auth.FacebookAuthProvider.PROVIDER_ID,
    firebase.auth.TwitterAuthProvider.PROVIDER_ID,
    firebase.auth.GithubAuthProvider.PROVIDER_ID,
    firebase.auth.EmailAuthProvider.PROVIDER_ID,
    firebase.auth.PhoneAuthProvider.PROVIDER_ID
  ],
  // Terms of service url.
  tosUrl: '<your-tos-url>',
  // Privacy policy url.
  privacyPolicyUrl: '<your-privacy-policy-url>'
};

Cuối cùng, kết xuất giao diện FirebaseUI Auth:

// The start method will wait until the DOM is loaded.
ui.start('#firebaseui-auth-container', uiConfig);

Nâng cấp người dùng ẩn danh

Cho phép nâng cấp người dùng ẩn danh

Khi người dùng ẩn danh đăng nhập hoặc đăng ký bằng tài khoản vĩnh viễn, bạn muốn đảm bảo người dùng có thể tiếp tục những gì họ đang làm trước khi đăng ký. Để làm như vậy, chỉ cần đặt autoUpgradeAnonymousUsers thành true khi bạn định cấu hình giao diện người dùng đăng nhập (tùy chọn này bị tắt theo mặc định).

Xử lý xung đột hợp nhất nâng cấp người dùng ẩn danh

Có những trường hợp khi người dùng, ban đầu đăng nhập ẩn danh, cố gắng nâng cấp lên người dùng Firebase hiện có. Vì người dùng hiện tại không thể được liên kết với một người dùng hiện có khác, nên FirebaseUI sẽ kích hoạt lệnh gọi lại signInFailure với mã lỗi firebaseui/anonymous-upgrade-merge-conflict khi điều trên xảy ra. Đối tượng lỗi cũng sẽ chứa thông tin xác thực vĩnh viễn. Đăng nhập bằng thông tin đăng nhập vĩnh viễn phải được kích hoạt trong lệnh gọi lại để hoàn tất đăng nhập. Trước khi có thể hoàn tất đăng nhập qua auth.signInWithCredential(error.credential) , bạn phải lưu dữ liệu của người dùng ẩn danh và xóa người dùng ẩn danh. Sau đó, sau khi hoàn tất đăng nhập, hãy sao chép lại dữ liệu cho người dùng không ẩn danh. Một ví dụ dưới đây minh họa cách thức hoạt động của quy trình này.

// Temp variable to hold the anonymous user data if needed.
var data = null;
// Hold a reference to the anonymous current user.
var anonymousUser = firebase.auth().currentUser;
ui.start('#firebaseui-auth-container', {
  // Whether to upgrade anonymous users should be explicitly provided.
  // The user must already be signed in anonymously before FirebaseUI is
  // rendered.
  autoUpgradeAnonymousUsers: true,
  signInSuccessUrl: '<url-to-redirect-to-on-success>',
  signInOptions: [
    firebase.auth.GoogleAuthProvider.PROVIDER_ID,
    firebase.auth.FacebookAuthProvider.PROVIDER_ID,
    firebase.auth.EmailAuthProvider.PROVIDER_ID,
    firebase.auth.PhoneAuthProvider.PROVIDER_ID
  ],
  callbacks: {
    // signInFailure callback must be provided to handle merge conflicts which
    // occur when an existing credential is linked to an anonymous user.
    signInFailure: function(error) {
      // For merge conflicts, the error.code will be
      // 'firebaseui/anonymous-upgrade-merge-conflict'.
      if (error.code != 'firebaseui/anonymous-upgrade-merge-conflict') {
        return Promise.resolve();
      }
      // The credential the user tried to sign in with.
      var cred = error.credential;
      // Copy data from anonymous user to permanent user and delete anonymous
      // user.
      // ...
      // Finish sign-in after data is copied.
      return firebase.auth().signInWithCredential(cred);
    }
  }
});

Bước tiếp theo

  • Để biết thêm thông tin về cách sử dụng và tùy chỉnh FirebaseUI, hãy truy cập README .
  • Nếu bạn tìm thấy sự cố trong FirebaseUI và muốn báo cáo, hãy sử dụng trình theo dõi sự cố GitHub .