Firebase:使用phoneNumber重新验证

时间:2019-02-12 11:36:58

标签: firebase firebase-authentication react-native-firebase

我知道我可以使用这样的电子邮件重新进行身份验证。

var user = firebase.auth().currentUser;
var credentials = firebase.auth.EmailAuthProvider.credential(
  user.email,
  'yourpassword'
);
user.reauthenticateWithCredential(credentials);

但是,如果我使用phoneNumber作为登录方法,该如何重新认证?

2 个答案:

答案 0 :(得分:0)

这与您使用电话号码登录的方式非常相似。您可以通过2种方式做到这一点:

使用reauthenticateWithPhoneNumber

const recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
    container, parameters, firebase.app());
recaptchaVerifier.render();
user.reauthenticateWithPhoneNumber(user.phoneNumber, recaptchaVerifier)
  .then((confirmationResult) => {
    return confirmationResult.confirm(prompt('Enter your SMS code'));
  })
  .then((userCredential) => {
    // User successfully reauthenticated.
  });

使用reauthenticateWithCredential

const recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
    container, parameters, firebase.app());
recaptchaVerifier.render();
const phoneAuthProvider = new firebase.auth.PhoneAuthProvider(auth);
phoneAuthProvider.verifyPhoneNumber(user.phoneNumber, recaptchaVerifier)
  .then((verificationId) => {
    const credential = firebase.auth.PhoneAuthProvider.credential(
        verificationId, prompt('Enter your code'));
    return user.reauthenticateWithCredential(credential);
  })
  .then((userCredential) => {
    // User successfully reauthenticated.
  });

答案 1 :(得分:0)

在React Native中使用expo-firebase-recaptcha

import React, { useState, useEffect, useRef } from 'react';
import { Alert, Text, TextInput, TouchableOpacity, View } from 'react-native';
import * as firebase from 'firebase';
import { FirebaseRecaptchaVerifierModal } from "expo-firebase-recaptcha";


const firebaseConfig = {
  // your firebaseConfig object
  //...
};

const Reauthentication = () => {

  const recaptchaRef = useRef();

  const [code, setCode] = useState("");
  const [verificationId, setVerificationId] = useState();

  useEffect(() => {
    (async () => {
      const user = firebase.auth().currentUser;
      const result = await user.reauthenticateWithPhoneNumber(user.phoneNumber, recaptchaRef.current);
      setVerificationId(result);
    })()
  }, []);


  const reauthenticate = () => {
    verificationId.confirm(code)
    .then((userCredential) => {
      // User is reauthenticated
    })
    .catch((err) => {
      Alert.alert(err);
    })
  }

  return (
    <View style={ styles.container }>
      <FirebaseRecaptchaVerifierModal
        ref={ recaptchaRef }
        firebaseConfig={ firebaseConfig }
      />
      <TextInput
        keyboardType="numeric"
        value={ code }
        onChangeText={ (text) => setCode(text) }
      />
      <TouchableOpacity onPress={ reauthenticate }>
        <Text>Reauthorize</Text>
      </TouchableOpacity>
    </View>
  )
}

export default Reauthentication;