Authenticate on Firebase with phone number

15,481

Solution 1

Firebase is now supporting auth with Phone number: https://firebase.google.com/docs/auth/web/phone-auth

UPDATE: The link is for the official doku so pleas read there all instructions because.

I would recommend to use the firebaseui library that does all the auth UI stuff for you. Here is the web version: https://github.com/firebase/firebaseui-web There are also some for the Android and iOS projects.

Here is also a demo application you can use to start your own one: https://github.com/TarikHuber/react-most-wanted

It has also a running demo: https://www.react-most-wanted.com/ You can there try out all of the auth methods.

The actual implementation is pretty simple if you use the firebaseui. Here is mine in a React Component.

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {injectIntl} from 'react-intl';
import { Activity } from '../../components/Activity';
import muiThemeable from 'material-ui/styles/muiThemeable';
import { push } from 'react-router-redux';
import firebase from 'firebase';
import firebaseui from 'firebaseui';
import {firebaseAuth} from '../../utils/firebase';

var authUi = new firebaseui.auth.AuthUI(firebaseAuth);

class SignIn extends Component {

  componentDidMount() {
    const {router, browser}= this.props;

    const redirect =((router || {}).location || {}).search;

    var uiConfig = {
      signInSuccessUrl: redirect.slice(1),
      signInFlow: browser.greaterThan.medium?'popup':'redirect',
      callbacks: {
        signInSuccess: function(user, credentials, redirect) {

          push(redirect || '/');

          //To avoid page reload on single page applications
          return false;
        }
      },
      signInOptions: [
        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
      ]
    };

    authUi.start('#firebaseui-auth', uiConfig);
    
  }

  componentWillUnmount() {
    authUi.reset();
  }

  render(){

    const  {intl} = this.props;

    return (
      <Activity
        title={intl.formatMessage({id: 'sign_in'})}>
        <div style={{paddingTop: 35, width: '100%'}}>
          <div id="firebaseui-auth" style={{width: '100%'}}></div>
        </div>
      </Activity>
    );

  }

}


SignIn.propTypes = {
  push: PropTypes.func.isRequired,
  intl: PropTypes.object.isRequired,
  router: PropTypes.object.isRequired,
  muiTheme: PropTypes.object.isRequired,
};


const mapStateToProps = (state) => {
  const {router, browser } = state;
  return {
    router,
    browser
  };
};


export default connect(
  mapStateToProps,
  { push}
)(injectIntl(muiThemeable()(SignIn)));

Solution 2

Just came across this question.. you can just add your domain to the end of phone number and still make it a email. [email protected]. Make sure to add this for signup and login. This is what im doing. The only downside of this approachis that you can't use firebase's provided functionality to send password reset emails to users. You have to implement your own service service to provide that.

Solution 3

You can use the custom token, wich is totally arbitrary datas

firebase doc

Solution 4

My usecase is different. I have to allow my users to perform login via mail and phone number both. Here how I am doing it:

Store emailId and phone number separately in Firebase Database.

Now for login via email and password:

  1. Using inbuilt method of signInWithEmailAndpassword

For login via phone no and password:

  1. Fetch Email id of user from Firebase database by passing user provided phone no
  2. If no email id returns, show error that phone no is not mapped to any account or account doesn't exist
  3. Once you receive email id, call signInWithEmailAndpassword and pass received email and user provided password

This is just a workaround which I found. I am still able to use reset password feature of Firebase :)

Share:
15,481
Devous
Author by

Devous

Updated on June 09, 2022

Comments

  • Devous
    Devous about 2 years

    I have gone though the doc of Firebase, and it seems that we need to provide an email to authenticate a user.

    However I rely on phone number.

    Is there a way to do this ?

  • Devous
    Devous about 9 years
    Meaning that I have no other choice than renting a server?
  • leo
    leo almost 9 years
    Yes why not! Very pragmatic and no less secure. The way I am doing it is I generate a temporary random password (doesn't matter really), then create the user with the phone based fake email address and the dummy password. In the meantime I've sent the verification code via SMS. Now the user is presented with a "login" screen where they need to enter the code, I then call the Firebase "changePassword" API method to set the password to that code and I log them in.<br/> Regardless, I make the code only valid for a limited time e.g. 24 hours, after that they need to request a new code.
  • mark922
    mark922 about 8 years
    Firebase provides Custom Authentication. You should design your own authentication rather than converting a phone number to an email id. It will save you a lot of trouble when you have to scale up.
  • vzhen
    vzhen almost 8 years
    @LeovandenBulck how you handle if users have forgot their password?
  • leo
    leo almost 8 years
    @vzhen Yes true, I found out about that later, but by then the customer already dropped the whole idea of phone based auth. A few days development down the drain but anyway better kill a bad idea when it's half implemented than carry on with it till the end ... it was a bad idea for the use case, way too complicated and based on false premises. Now if you dare go off the beaten track and want to try something innovative (and supposedly more secure) then try passwordless auth: medium.com/javascript-scene/…
  • Baum mit Augen
    Baum mit Augen about 7 years
    Please explain how to do this in the answer itself.
  • Tarik Huber
    Tarik Huber almost 7 years
    @ShylendraMadda can you provide more informations about your error?
  • Shailendra Madda
    Shailendra Madda almost 7 years
    When I click on Run code snippet button showing Error message: { "message": "Uncaught SyntaxError: Unexpected token import", "filename": "https://stacksnippets.net/js", "lineno": 13, "colno": 9 }
  • Tarik Huber
    Tarik Huber almost 7 years
    The code snipped just shows the portion of the code. You need the whole project to make it work. You can check it here: github.com/TarikHuber/react-most-wanted and run the demo here: react-most-wanted.com
  • Akhil Nambiar
    Akhil Nambiar over 6 years
    how would you send an OTP in this scenario to verify if the phone number entered by the user is correct/belongs to him?
  • Irfan Raza
    Irfan Raza over 6 years
    @AqeelSmith Firebase now official supports login through mobile no. Please use that. Whatever I mentioned is just a workaround for old firebase library.
  • Akhil Nambiar
    Akhil Nambiar over 6 years
    Hi Irfan , it only allows using the phone number , there is still no option to login using phone number and password.