我在项目中使用react-native-firebase
v5.6。
目标:在注册流程中,我让用户输入他们的电话号码,然后向该电话号码发送 OTP。我希望能够将用户输入的代码与从 Firebase 发送的代码进行比较,以便能够授予注册后续步骤的输入权限。
问题:用户获得短信 OTP 和所有内容,但firebase.auth().verifyPhoneNumber(number).on('state_changed', (phoneAuthSnapshot => {})
返回的phoneAuthSnapshot
对象,它没有给出 firebase 发送的代码的值,因此没有什么可以比较用户输入的代码。但是,verificationId
属性有一个值。下面是从上述方法返回的对象:
'Verification code sent', {
verificationId: 'AM5PThBmFvPRB6x_tySDSCBG-6tezCCm0Niwm2ohmtmYktNJALCkj11vpwyou3QGTg_lT4lkKme8UvMGhtDO5rfMM7U9SNq7duQ41T8TeJupuEkxWOelgUiKf_iGSjnodFv9Jee8gvHc50XeAJ3z7wj0_BRSg_gwlN6sumL1rXJQ6AdZwzvGetebXhZMb2gGVQ9J7_JZykCwREEPB-vC0lQcUVdSMBjtig',
code: null,
error: null,
state: 'sent'
}
这是我在屏幕上的实现:
firebase
.firestore()
.collection('users')
.where('phoneNumber', '==', this.state.phoneNumber)
.get()
.then((querySnapshot) => {
if (querySnapshot.empty === true) {
// change status
this.setState({ status: 'Sending confirmation code...' });
// send confirmation OTP
firebase.auth().verifyPhoneNumber(this.state.phoneNumber).on(
'state_changed',
(phoneAuthSnapshot) => {
switch (phoneAuthSnapshot.state) {
case firebase.auth.PhoneAuthState.CODE_SENT:
console.log('Verification code sent', phoneAuthSnapshot);
this.setState({ status: 'Confirmation code sent.', confirmationCode: phoneAuthSnapshot.code });
break;
case firebase.auth.PhoneAuthState.ERROR:
console.log('Verification error: ' + JSON.stringify(phoneAuthSnapshot));
this.setState({ status: 'Error sending code.', processing: false });
break;
}
},
(error) => {
console.log('Error verifying phone number: ' + error);
}
);
}
})
.catch((error) => {
// there was an error
console.log('Error during firebase operation: ' + JSON.stringify(error));
});
如何获取从 Firebase 发送的代码以便进行比较?
正如 @christos-lytras 在他们的答案中所做的那样,验证码不会暴露给您的应用程序。
这样做是出于安全原因,因为向设备本身提供用于带外身份验证的代码将允许知识渊博的用户从内存中取出代码并进行身份验证,就好像他们可以访问该电话号码一样。
一般操作流程为:
- 获取要验证的电话号码
- 将该号码与
verifyPhoneNumber()
一起使用,并缓存它返回的验证 ID - 提示用户输入代码(或自动检索代码(
- 使用
firebase.auth.PhoneAuthProvider.credential(id, code)
将 ID 和用户的输入捆绑在一起作为凭据 - 尝试使用该凭据登录
firebase.auth().signInWithCredential(credential)
在源代码中,还使用verifyPhoneNumber(phoneNumber)
方法的on(event, observer, errorCb, successCb)
侦听器。不过,此方法还支持使用 Promise 侦听结果,这样您就可以链接到 Firebase 查询。如下所示。
发送验证码:
firebase
.firestore()
.collection('users')
.where('phoneNumber', '==', this.state.phoneNumber)
.get()
.then((querySnapshot) => {
if (!querySnapshot.empty) {
// User found with this phone number.
throw new Error('already-exists');
}
// change status
this.setState({ status: 'Sending confirmation code...' });
// send confirmation OTP
return firebase.auth().verifyPhoneNumber(this.state.phoneNumber)
})
.then((phoneAuthSnapshot) => {
// verification sent
this.setState({
status: 'Confirmation code sent.',
verificationId: phoneAuthSnapshot.verificationId,
showCodeInput: true // shows input field such as react-native-confirmation-code-field
});
})
.catch((error) => {
// there was an error
let newStatus;
if (error.message === 'already-exists') {
newStatus = 'Sorry, this phone number is already in use.';
} else {
// Other internal error
// see https://firebase.google.com/docs/reference/js/firebase.firestore.html#firestore-error-code
// see https://firebase.google.com/docs/reference/js/firebase.auth.PhoneAuthProvider#verify-phone-number
// probably 'unavailable' or 'deadline-exceeded' for loss of connection while querying users
newStatus = 'Failed to send verification code.';
console.log('Unexpected error during firebase operation: ' + JSON.stringify(error));
}
this.setState({
status: newStatus,
processing: false
});
});
处理用户来源的验证码:
codeInputSubmitted(code) {
const { verificationId } = this.state;
const credential = firebase.auth.PhoneAuthProvider.credential(
verificationId,
code
);
// To verify phone number without interfering with the existing user
// who is signed in, we offload the verification to a worker app.
let fbWorkerApp = firebase.apps.find(app => app.name === 'auth-worker')
|| firebase.initializeApp(firebase.app().options, 'auth-worker');
fbWorkerAuth = fbWorkerApp.auth();
fbWorkerAuth.setPersistence(firebase.auth.Auth.Persistence.NONE); // disables caching of account credentials
fbWorkerAuth.signInWithCredential(credential)
.then((userCredential) => {
// userCredential.additionalUserInfo.isNewUser may be present
// userCredential.credential can be used to link to an existing user account
// successful
this.setState({
status: 'Phone number verified!',
verificationId: null,
showCodeInput: false,
user: userCredential.user;
});
return fbWorkerAuth.signOut().catch(err => console.error('Ignored sign out error: ', err);
})
.catch((err) => {
// failed
let userErrorMessage;
if (error.code === 'auth/invalid-verification-code') {
userErrorMessage = 'Sorry, that code was incorrect.'
} else if (error.code === 'auth/user-disabled') {
userErrorMessage = 'Sorry, this phone number has been blocked.';
} else {
// other internal error
// see https://firebase.google.com/docs/reference/js/firebase.auth.Auth.html#sign-inwith-credential
userErrorMessage = 'Sorry, we couldn't verify that phone number at the moment. '
+ 'Please try again later. '
+ 'nnIf the issue persists, please contact support.'
}
this.setState({
codeInputErrorMessage: userErrorMessage
});
})
}
接口参考:
verifyPhoneNumber()
- React Native 或 FirebasePhoneAuthProvider.credential(id, code)
- 火力基地signInWithCredential()
- React Native 或 Firebase
建议的代码输入组件:
react-native-confirmation-code-field
Firebase firebase.auth.PhoneAuthProvider不会给你比较的代码,你必须使用verificationId
来验证用户输入的verificationCode
。Firebase 文档中有一个基本示例,即使用firebase.auth.PhoneAuthProvider.credential
然后尝试使用这些凭据登录firebase.auth().signInWithCredential(phoneCredential)
:
firebase
.firestore()
.collection('users')
.where('phoneNumber', '==', this.state.phoneNumber)
.get()
.then((querySnapshot) => {
if (querySnapshot.empty === true) {
// change status
this.setState({ status: 'Sending confirmation code...' });
// send confirmation OTP
firebase.auth().verifyPhoneNumber(this.state.phoneNumber).on(
'state_changed',
(phoneAuthSnapshot) => {
switch (phoneAuthSnapshot.state) {
case firebase.auth.PhoneAuthState.CODE_SENT:
console.log('Verification code sent', phoneAuthSnapshot);
// this.setState({ status: 'Confirmation code sent.', confirmationCode: phoneAuthSnapshot.code });
// Prompt the user the enter the verification code they get and save it to state
const userVerificationCodeInput = this.state.userVerificationCode;
const phoneCredentials = firebase.auth.PhoneAuthProvider.credential(
phoneAuthSnapshot.verificationId,
userVerificationCodeInput
);
// Try to sign in with the phone credentials
firebase.auth().signInWithCredential(phoneCredentials)
.then(userCredentials => {
// Sign in successfull
// Use userCredentials.user and userCredentials.additionalUserInfo
})
.catch(error => {
// Check error code to see the reason
// Expect something like:
// auth/invalid-verification-code
// auth/invalid-verification-id
});
break;
case firebase.auth.PhoneAuthState.ERROR:
console.log('Verification error: ' + JSON.stringify(phoneAuthSnapshot));
this.setState({ status: 'Error sending code.', processing: false });
break;
}
},
(error) => {
console.log('Error verifying phone number: ' + error);
}
);
}
})
.catch((error) => {
// there was an error
console.log('Error during firebase operation: ' + JSON.stringify(error));
});
若要使用多重身份验证,必须在用户选择更新设置并启用 MFA 时,最初或稍后在后台与主要(在本例中(电子邮件登录提供程序一起创建电话登录提供程序。然后在用户登录时使用电子邮件登录提供程序链接它,如下所示;
const credential = auth.PhoneAuthProvider.credential(verificationId, code);
let userData = await auth().currentUser.linkWithCredential(credential);
不幸的是,Firebase不支持这一点。使用凭据登录后登录和注销可以工作,但非常混乱
我面临着同样的困难。我的目的只是验证用户的电话号码在此处输入图像描述,然后使用电子邮件和密码注册它们。经过长时间的紧张试验和错误方法,我找到了解决方案。但关键是我在我的安卓应用程序中使用 firebase。它所做的是
- 我首先尝试将 OTP 与用户输入的 OTP 匹配,但是 firebase 在后端提供给我们的 OTP 使用一些逻辑加密,并且该逻辑在文档中没有任何地方,所以我无法解密它。
- 第二种方法对我有用。我所做的是,我使用电话授权登录用户,当任务成功时,我删除了那里新创建的用户,然后使用电子邮件ID和密码登录用户。