Firebase Auth Using Phone Number and Password

Firebase Auth using phone number and password

Firebase phone authentication is using OTP(one time password). This way there is no hassle for the user to remember the password. Once authenticated, you will be registered. The sms code acts as a password. But that is for one time. Usually , users prefer such behaviour in which you dont have to remember the passwords. If you are still looking for the way you want, see this link and create a custom authentication method.
https://firebase.google.com/docs/auth/android/custom-auth

Phone Number with Password Authentication using Firebase

Create cloud function with following code

const functions = require('firebase-functions');
const firebase = require('firebase');
const admin = require('firebase-admin');

admin.initializeApp();
firebase.initializeApp({
//Add config for web-app here
//Required because Admin SDK doesn't include signInWithEmailAndPassword method
});

exports.signInWithPhoneAndPassword = functions.https.onCall(async (data, context) => {
const phoneNumber = data.phone;
if (phoneNumber === undefined) {
return {'s':400,'m':'Bad argument: no phone number'};
}
const user = await admin.auth().getUserByPhoneNumber(phoneNumber);
const pass = data.password;
try {
await firebase.auth().signInWithEmailAndPassword(user.email, pass);
} catch (e) {
return {'s':400,'m':'Wrong password'};
}
const token = await admin.auth().createCustomToken(user.uid, {'devClaim':true}); //developer claims, optional param
return {'s':200,'t':token};
});

On client side call this function, and if it returns object with "s"==200 use token with signInWithCustomToken (Calling a Cloud Function from Android through Firebase)

How to link Phone with Email and Password Authentication in Firebase?

If you do this, the Firebase creates two different users.

That's the expected behavior since you are using two separate types of authentication.

How can I combine them so that it appears as a single account?

If you want to have only one, then you should link both of them together into a single account. According to the official documentation regarding account linking, first, you need to get the existing credentials:

val authCredential = EmailAuthProvider.getCredential(email, password)

For Java users:

AuthCredential authCredential = EmailAuthProvider.getCredential(email, password);

And then simply use the FirebaseUser#linkWithCredential(AuthCredential credential) method like in the following lines of code:

val auth = FirebaseAuth.getInstance()
auth.currentUser!!.linkWithCredential(credential).addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Log.d(TAG, "linkWithCredential:success")
val user = task.result!!.user
updateUI(user)
} else {
Log.w(TAG, "linkWithCredential:failure", task.exception)
Toast.makeText(this, "Authentication failed.", Toast.LENGTH_SHORT).show()
updateUI(null)
}
}

And for Java users:

FirebaseAuth auth = FirebaseAuth.getInstance();
auth.getCurrentUser().linkWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "linkWithCredential:success");
FirebaseUser user = task.getResult().getUser();
updateUI(user);
} else {
Log.w(TAG, "linkWithCredential:failure", task.getException());
Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});

Firebase Auth - forgotten password with phone auth

You can use verifyPhoneNumber:UIDelegate:completion: to send the users another SMS message for verification and then sign in using the verificationID.

Official doc on how to do that -> https://firebase.google.com/docs/auth/ios/phone-auth#send-a-verification-code-to-the-users-phone.

PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in
if let error = error {
self.showMessagePrompt(error.localizedDescription)
return
}
// Sign in using the verificationID and the code sent to the user
// ...
}

OR

If you have a server, you can use Firebase admin SDK, available in Node.js, Java, Python, Go, and C#, to update the user's password property just with user's uid.

Example in Node.js:

admin.auth().updateUser(uid, {
password: "YOUR_NEW_PWD"
})
.then((userRecord) => {
console.log('Successfully updated user', userRecord.toJSON());
})
.catch((error) => {
console.log('Error updating user:', error);
});

Authenticate using phone, username and password in Firebase

you can firebase client sdk to implement this requirement.

But the sign up and login will work in 2 different ways.

You must enable phone, email/password feature.

during the sign up/login you need to send the verification code to the phone number and

the password auth can be programmed easily depending upon what client you are using.

Since you already done this it will be easy for you it seems

UPDATE 1

well for one case you could store the username, password and phone number in firebase.
so when the user gets an sms and verify on that you could create a username and password signup (but i don't see one so what you must do is append @someemail.com at the end of the username to make it like a email, and you can perfectly do this since you don't have email related things in your app).

Now when they login using their phone number you can map that email related to that phone number and use signInWithEmailAndPassword feature in client sdk with the password associated with the phone number and thus in the front end it may seems that you are logging in using phone number but in the back end you have extra layer of authenticity via phone-email-password combination.

I believe now you got me.



Related Topics



Leave a reply



Submit