Nouf
Nouf

Reputation: 21

Retrieve SMS code sent to user's phone - Firebase SMS Authentication

I want to get the actual code that was sent by Firebase to the user.

I tried using the following piece of code:

PhoneAuthCredential credential = 
    PhoneAuthProvider.getCredential(verificationid, usercode);

String ActualCode = credential.getSmsCode();

However this doesn't seem to work, as it looks like getSmsCode() retrieves the code entered by the user.

Upvotes: 1

Views: 1184

Answers (2)

Asim Waheed
Asim Waheed

Reputation: 1

private PhoneAuthProvider.OnVerificationStateChangedCallbacks
            mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

        @Override
        public void onVerificationCompleted(@NonNull PhoneAuthCredential credential) {

            final String code = credential.getSmsCode();
            if (code != null) {

                PhoneAuthCredential authCredential = PhoneAuthProvider.getCredential(verificationID, code);
                firebaseAuth.signInWithCredential(authCredential)
                        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Toast.makeText(SignInActivity.this,
                                    "Login Successful", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }
    enter code here
        @Override
        public void onVerificationFailed(@NonNull FirebaseException e) {
            Toast.makeText(SignInActivity.this, "Verification Failed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCodeSent(@NonNull String s,
                               @NonNull PhoneAuthProvider.ForceResendingToken token) {

            super.onCodeSent(s, token);
            verificationID = s;
        }
    };

Upvotes: 0

Barak
Barak

Reputation: 1429

No, there isn't. And you should be happy about it.

Such API creates a potential security vulnerability for your users. Bad usage could lead hackers accessing your users' data. So it's a good decision by Google to not expose it.

However, if you're trying to achieve an Auto Sign-in functionality, know that on some devices Google Play services automatically detect the incoming verification SMS and perform verification without user action.

Read more here about the Auto Retrieval mechanism of Firebase SMS Auth.

Upvotes: 1

Related Questions