The backend is implemented based on firebase third-party platform registration

The backend is implemented based on firebase third-party platform registration

Foreword:

The current login and registration for overseas apps or websites generally support third-party accounts such as: Google, Facebook, Apple, etc. It happens that firebase supports the integration of these common social platform authentications and provides front-end and back-end SDKs, which is very convenient for docking. The following Introduce the simple login and registration process.

accomplish:

  1. Register a google account to enter the firebase background and create a projectinsert image description here

  2. Create an application under the project, optional according to the actual situation, Android, ios, web type.insert image description here

  3. Click the service account to generate the backend private key file and save itinsert image description here

  4. Simply implement a tool class:
    dependency:

    <dependency>
      <groupId>com.google.firebase</groupId>
      <artifactId>firebase-admin</artifactId>
      <version>8.1.0</version>
    </dependency>
    
    package com.example.demo.utils;
    
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.FirebaseAuthException;
    import com.google.firebase.auth.UserRecord;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    
    
    public class FirebaseAuthUtils {
          
          
        private static final Logger log = LoggerFactory.getLogger(FirebaseAuthUtils.class);
    
        static {
          
          
            try {
          
          
                FirebaseOptions options = null;
                FileInputStream serviceAccount =
                        new FileInputStream("path/to/serviceAccountKey.json");
                options = FirebaseOptions.builder()
                        .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                        .build();
                FirebaseApp.initializeApp(options);
            } catch (IOException e) {
          
          
               log.error(e.getMessage(), e);
            }
        }
    
        /**
         * 验证登录token
         *
         * @param idToken
         * @return
         */
        public static String verifyIdToken(String idToken) {
          
          
            String uid = null;
            try {
          
          
                uid = FirebaseAuth.getInstance().verifyIdToken(idToken).getUid();
            } catch (FirebaseAuthException e) {
          
          
                log.error(e.getMessage(), e);
            }
            return uid;
        }
    
    
        /**
         * 获取用户基本信息
         *
         * @param uid
         * @return
         */
        public static UserRecord getUserById(String uid) {
          
          
            UserRecord userRecord = null;
            try {
          
          
                userRecord = FirebaseAuth.getInstance().getUser(uid);
            } catch (FirebaseAuthException e) {
          
          
                log.error(e.getMessage(), e);
            }
            return userRecord;
        }
    
    }
    
    
  5. Simply draw a timing diagram
    insert image description here

  6. The following is an example of a request:
    I run a pure front-end authentication project locally . After running it, I can log in to the browser-side interface and request to see the idToken I got. After getting it, I find that it is a content in jwt format, which can be decoded directly. However, it is recommended to call the verifyIdToken of the above tool class to obtain the user id to prevent data from being tampered with. After obtaining the uid, verify whether the user exists.
    insert image description here
    7. UserRecord class

    public class UserRecord implements UserInfo {
          
          
    
      private static final String PROVIDER_ID = "firebase";
      private static final Map<String, String> REMOVABLE_FIELDS = ImmutableMap.of(
          "displayName", "DISPLAY_NAME",
          "photoUrl", "PHOTO_URL");
      static final String CUSTOM_ATTRIBUTES = "customAttributes";
      private static final int MAX_CLAIMS_PAYLOAD_SIZE = 1000;
    
      private final String uid;
      private final String tenantId;
      private final String email;
      private final String phoneNumber;
      private final boolean emailVerified;
      private final String displayName;
      private final String photoUrl;
      private final boolean disabled;
      private final ProviderUserInfo[] providers;
      private final long tokensValidAfterTimestamp;
      private final UserMetadata userMetadata;
      private final Map<String, Object> customClaims;
    }  
    

    This is the user class that comes with the sdk. The main purpose of this class is to obtain the user's third-party account information, such as email, mobile phone, avatar, etc.

important point:

  1. The same account is bound to multiple platforms, such as: to bind google and facebook accounts at the same time, it needs to be operated in the background of firebase. insert image description hereAfter opening this option, the email field of the UserRecord class may be empty, which needs to be obtained from the providers array

  2. About the avatar photoUrl field, the thumbnail may be obtained. This is because the avatar address of each platform will have a thumbnail parameter. The following introduces a method for google and facebook to get the original image and replace the thumbnail parameter:

    UserRecord user = FirebaseAuthUtils.getUserById(uid);
    // 谷歌
    String path = user.getPhotoUrl().replace("s96-c", "s500-c");
    // facebook
    String concat = registerDTO.getPhotoUrl().indexOf("?") > 0 ? "&" : "?";
    path = user.getPhotoUrl()+ concat + "type=large");
    
    

Guess you like

Origin blog.csdn.net/Arhhhhhhh/article/details/132609027