Create cell phone number authentication with Fireb

2019-02-20 09:35发布

At present, the options on the Firebase website limit you to prepackaged solutions for authenticating users through Facebook or a person's email, etc. I wish to allow user to login and authenticate using their cell phone number, much like Snapchat allows.

Is there a pre-packaged solution for this? How can this be built out?

3条回答
Animai°情兽
2楼-- · 2019-02-20 10:19

It is possible. But currently only for iOS/Web. The implementation for Android should be done soon as well. Check firebase docs. https://firebase.google.com/docs/auth/web/phone-auth

查看更多
倾城 Initia
3楼-- · 2019-02-20 10:23

now phone auth is available in firebase.Here is Code for Phone Auth using Firebase:

EditText phoneNum,Code;// two edit text one for enter phone number other for enter OTP code
Button sent_,Verify;  // sent button to request for verification and verify is for to verify code
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private FirebaseAuth mAuth;
private String mVerificationId;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_phone_number_auth);// layout 


    phoneNum =(EditText) findViewById(R.id.fn_num);
    Code =(EditText) findViewById(R.id.code);

    sent_ =(Button)findViewById(R.id.sent_nu);
    Verify =(Button)findViewById(R.id.verify);

    callback_verificvation();                   ///function initialization

    mAuth = FirebaseAuth.getInstance();


    sent_.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String num=phoneNum.getText().toString();
            startPhoneNumberVerification(num);          // call function for receive OTP 6 digit code
        }
    });
    Verify.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String code=Code.getText().toString();
            verifyPhoneNumberWithCode(mVerificationId,code);     //call function for verify code 

        }
    });
}

private void startPhoneNumberVerification(String phoneNumber) {
    // [START start_phone_auth]
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phoneNumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            this,               // Activity (for callback binding)
            mCallbacks);        // OnVerificationStateChangedCallbacks
    // [END start_phone_auth]


}

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information

                        FirebaseUser user = task.getResult().getUser();
                        Toast.makeText(getApplicationContext(), "sign in successfull", Toast.LENGTH_SHORT).show();
                        // [START_EXCLUDE]


                    } else {
                        // Sign in failed, display a message and update the UI

                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            // The verification code entered was invalid

                        }

                    }
                }
            });
}
private void verifyPhoneNumberWithCode(String verificationId, String code) {
    // [START verify_with_code]
    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
    // [END verify_with_code]
    signInWithPhoneAuthCredential(credential);
}


private void callback_verificvation() {

    mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

        @Override
        public void onVerificationCompleted(PhoneAuthCredential credential) {
            // This callback will be invoked in two situations:
            // 1 - Instant verification. In some cases the phone number can be instantly
            //     verified without needing to send or enter a verification code.
            // 2 - Auto-retrieval. On some devices Google Play services can automatically
            //     detect the incoming verification SMS and perform verificaiton without
            //     user action.
            // [START_EXCLUDE silent]


            // [START_EXCLUDE silent]

            signInWithPhoneAuthCredential(credential);
        }

        @Override
        public void onVerificationFailed(FirebaseException e) {
            // This callback is invoked in an invalid request for verification is made,
            // for instance if the the phone number format is not valid.
            // [START_EXCLUDE silent]


            if (e instanceof FirebaseAuthInvalidCredentialsException) {
                // Invalid request


                // [END_EXCLUDE]
            } else if (e instanceof FirebaseTooManyRequestsException) {
                // The SMS quota for the project has been exceeded

            }


        }

        @Override
        public void onCodeSent(String verificationId,
                               PhoneAuthProvider.ForceResendingToken token) {
            // The SMS verification code has been sent to the provided phone number, we
            // now need to ask the user to enter the code and then construct a credential
            // by combining the code with a verification ID.


            // Save verification ID and resending token so we can use them later
            mVerificationId = verificationId;
            mResendToken = token;


        }
    };
查看更多
够拽才男人
4楼-- · 2019-02-20 10:34

That is currently not supported. Phone number auth is a tricky feature to implement from a privacy, security and product perspective. That said, if you wish to build it, you will have to implement your own mechanism to send SMS messages with a unique short lived code (corresponding to an allocated uid for a specific phone number) to users using a service like Twilio. You also have to protect against phishing attacks from apps trying to impersonate your app (in the 3 supported platforms) and tricking users to enter the SMS code into their app. Not to mention you have to protect against abuse (malicious users sending SMS messages from your app). Finally when the user redeem the SMS code, you can return a custom token (associated with the allocated uid) which is currently supported by Firebase admin sdk and signInWithCustomToken on the client side completing the sign-in process. This is still an oversimplification of the issue. I suggest you request that feature in the Firebase Google group forum.

查看更多
登录 后发表回答