许多应用程序要求其用户进行身份验证。因此,为了验证应用程序的目的,请在其应用程序内部使用电话号码验证。在电话身份验证中,用户必须使用其电话号码验证其身份。在应用内部,用户必须输入其电话号码,然后他的手机号码将收到验证码。他必须输入该验证码并验证他的身份。这就是电话身份验证的工作方式。 Firebase为身份验证用户提供了多种方式,例如Google,电子邮件和密码,电话等。在本文中,我们将介绍使用Firebase在我们的应用程序中实现电话身份验证的方法。
我们将在本文中构建什么?
我们将创建一个具有两个屏幕的简单应用程序。第一个屏幕将是我们的“验证”屏幕,用户必须在该屏幕上添加他的电话号码。添加电话号码后,用户将单击“获取OTP”按钮,然后Firebase将使用上述号码发送OTP。收到该OTP后,用户必须在下面的文本框中输入该OTP,然后单击下面的按钮以确认输入的OTP。单击验证按钮后,Firebase将验证OTP并仅在输入的OTP正确时才允许用户进入主屏幕,否则用户将收到错误消息。注意,我们将使用Java语言实现该项目。
分步实施
步骤1:创建一个新项目
要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。
第2步:将您的应用连接到Firebase
在Android Studio中创建新项目后,将您的应用连接到Firebase。用于将您的应用程序连接到Firebase。导航到顶部栏上的“工具”。之后,单击Firebase。右侧将打开一个新窗口。在该窗口内,单击身份验证,然后单击电子邮件和密码身份验证。
单击电子邮件和密码身份验证后,您将看到以下屏幕。在此屏幕内,单击第一个选项以连接到Firebase,然后单击第二个选项以将Firebase身份验证添加到您的应用程序。
步骤3:确认您的应用程式内已新增Firebase验证的相依性
将您的应用程序连接到Firebase之后。如果未添加,请确保在build.gradle文件中添加此依赖项。添加此依赖项后,同步您的项目。
Note: Make sure to add the exact dependency version in the above image because the latest dependency is not having the implementation for auto-detection of OTP.
步骤4:使用activity_main.xml文件
转到activity_main.xml文件,并参考以下代码。以下是activity_main.xml文件的代码。
XML
XML
Java
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskExecutors;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
// variable for FirebaseAuth class
private FirebaseAuth mAuth;
// variable for our text input
// field for phone and OTP.
private EditText edtPhone, edtOTP;
// buttons for generating OTP and verifying OTP
private Button verifyOTPBtn, generateOTPBtn;
// string for storing our verification ID
private String verificationId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// below line is for getting instance
// of our FirebaseAuth.
mAuth = FirebaseAuth.getInstance();
// initializing variables for button and Edittext.
edtPhone = findViewById(R.id.idEdtPhoneNumber);
edtOTP = findViewById(R.id.idEdtOtp);
verifyOTPBtn = findViewById(R.id.idBtnVerify);
generateOTPBtn = findViewById(R.id.idBtnGetOtp);
// setting onclick listner for generate OTP button.
generateOTPBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// below line is for checking weather the user
// has entered his mobile number or not.
if (TextUtils.isEmpty(edtPhone.getText().toString())) {
// when mobile number text field is empty
// displaying a toast message.
Toast.makeText(MainActivity.this, "Please enter a valid phone number.", Toast.LENGTH_SHORT).show();
} else {
// if the text field is not empty we are calling our
// send OTP method for getting OTP from Firebase.
String phone = "+91" + edtPhone.getText().toString();
sendVerificationCode(phone);
}
}
});
// initializing on click listener
// for verify otp button
verifyOTPBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// validating if the OTP text field is empty or not.
if (TextUtils.isEmpty(edtOTP.getText().toString())) {
// if the OTP text field is empty display
// a message to user to enter OTP
Toast.makeText(MainActivity.this, "Please enter OTP", Toast.LENGTH_SHORT).show();
} else {
// if OTP field is not empty calling
// method to verify the OTP.
verifyCode(edtOTP.getText().toString());
}
}
});
}
private void signInWithCredential(PhoneAuthCredential credential) {
// inside this method we are checking if
// the code entered is correct or not.
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
// if the code is correct and the task is successful
// we are sending our user to new activity.
Intent i = new Intent(MainActivity.this, HomeActivity.class);
startActivity(i);
finish();
} else {
// if the code is not correct then we are
// displaying an error message to the user.
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
private void sendVerificationCode(String number) {
// this method is used for getting
// OTP on user phone number.
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number, // first parameter is user's mobile number
60, // second parameter is time limit for OTP
// verification which is 60 seconds in our case.
TimeUnit.SECONDS, // third parameter is for initializing units
// for time period which is in seconds in our case.
TaskExecutors.MAIN_THREAD, // this task will be excuted on Main thread.
mCallBack // we are calling callback method when we recieve OTP for
// auto verification of user.
);
}
// callback method is called on Phone auth provider.
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
// initializing our callbacks for on
// verification callback method.
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
// below method is used when
// OTP is sent from Firebase
@Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
// when we receive the OTP it
// contains a unique id which
// we are storing in our string
// which we have already created.
verificationId = s;
}
// this method is called when user
// receive OTP from Firebase.
@Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
// below line is used for getting OTP code
// which is sent in phone auth credentials.
final String code = phoneAuthCredential.getSmsCode();
// checking if the code
// is null or not.
if (code != null) {
// if the code is not null then
// we are setting that code to
// our OTP edittext field.
edtOTP.setText(code);
// after setting this code
// to OTP edittext field we
// are calling our verifycode method.
verifyCode(code);
}
}
// this method is called when firebase doesn't
// sends our OTP code due to any error or issue.
@Override
public void onVerificationFailed(FirebaseException e) {
// displaying error message with firebase exception.
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
// below method is use to verify code from Firebase.
private void verifyCode(String code) {
// below line is used for getting getting
// credentials from our verification id and code.
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
// after getting credential we are
// calling sign in method.
signInWithCredential(credential);
}
}
XML
步骤5:在您的Manifest.xml文件中添加Internet权限
导航至应用程序> AndroidManifest.xml文件,然后向其添加以下权限。
XML格式
第6步:为我们的主页创建一个新的活动
导航到应用程序> Java >应用程序的程序包名称>右键单击应用程序的程序包名称,然后单击新建>活动>空活动并命名您的活动。在这里,我们将其命名为HomeActivity 。
步骤7:使用MainActivity。 Java文件
转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。
Java
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskExecutors;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
// variable for FirebaseAuth class
private FirebaseAuth mAuth;
// variable for our text input
// field for phone and OTP.
private EditText edtPhone, edtOTP;
// buttons for generating OTP and verifying OTP
private Button verifyOTPBtn, generateOTPBtn;
// string for storing our verification ID
private String verificationId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// below line is for getting instance
// of our FirebaseAuth.
mAuth = FirebaseAuth.getInstance();
// initializing variables for button and Edittext.
edtPhone = findViewById(R.id.idEdtPhoneNumber);
edtOTP = findViewById(R.id.idEdtOtp);
verifyOTPBtn = findViewById(R.id.idBtnVerify);
generateOTPBtn = findViewById(R.id.idBtnGetOtp);
// setting onclick listner for generate OTP button.
generateOTPBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// below line is for checking weather the user
// has entered his mobile number or not.
if (TextUtils.isEmpty(edtPhone.getText().toString())) {
// when mobile number text field is empty
// displaying a toast message.
Toast.makeText(MainActivity.this, "Please enter a valid phone number.", Toast.LENGTH_SHORT).show();
} else {
// if the text field is not empty we are calling our
// send OTP method for getting OTP from Firebase.
String phone = "+91" + edtPhone.getText().toString();
sendVerificationCode(phone);
}
}
});
// initializing on click listener
// for verify otp button
verifyOTPBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// validating if the OTP text field is empty or not.
if (TextUtils.isEmpty(edtOTP.getText().toString())) {
// if the OTP text field is empty display
// a message to user to enter OTP
Toast.makeText(MainActivity.this, "Please enter OTP", Toast.LENGTH_SHORT).show();
} else {
// if OTP field is not empty calling
// method to verify the OTP.
verifyCode(edtOTP.getText().toString());
}
}
});
}
private void signInWithCredential(PhoneAuthCredential credential) {
// inside this method we are checking if
// the code entered is correct or not.
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
// if the code is correct and the task is successful
// we are sending our user to new activity.
Intent i = new Intent(MainActivity.this, HomeActivity.class);
startActivity(i);
finish();
} else {
// if the code is not correct then we are
// displaying an error message to the user.
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
private void sendVerificationCode(String number) {
// this method is used for getting
// OTP on user phone number.
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number, // first parameter is user's mobile number
60, // second parameter is time limit for OTP
// verification which is 60 seconds in our case.
TimeUnit.SECONDS, // third parameter is for initializing units
// for time period which is in seconds in our case.
TaskExecutors.MAIN_THREAD, // this task will be excuted on Main thread.
mCallBack // we are calling callback method when we recieve OTP for
// auto verification of user.
);
}
// callback method is called on Phone auth provider.
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
// initializing our callbacks for on
// verification callback method.
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
// below method is used when
// OTP is sent from Firebase
@Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
// when we receive the OTP it
// contains a unique id which
// we are storing in our string
// which we have already created.
verificationId = s;
}
// this method is called when user
// receive OTP from Firebase.
@Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
// below line is used for getting OTP code
// which is sent in phone auth credentials.
final String code = phoneAuthCredential.getSmsCode();
// checking if the code
// is null or not.
if (code != null) {
// if the code is not null then
// we are setting that code to
// our OTP edittext field.
edtOTP.setText(code);
// after setting this code
// to OTP edittext field we
// are calling our verifycode method.
verifyCode(code);
}
}
// this method is called when firebase doesn't
// sends our OTP code due to any error or issue.
@Override
public void onVerificationFailed(FirebaseException e) {
// displaying error message with firebase exception.
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
// below method is use to verify code from Firebase.
private void verifyCode(String code) {
// below line is used for getting getting
// credentials from our verification id and code.
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
// after getting credential we are
// calling sign in method.
signInWithCredential(credential);
}
}
步骤8:研究HomeActivity
现在,我们已经对用户进行了身份验证,并开始进行家庭活动。现在,我们将在成功身份验证后向用户显示欢迎消息。为此,导航至应用程序> res>布局> activity_home.xml,然后将以下代码添加到其中。
XML格式
步骤9:在我们的Firebase控制台中启用Firebase电话身份验证
要在Firebase控制台中启用电话身份验证,请转到Firebase控制台。现在,单击“转到控制台”选项,然后导航到您的项目。之后,单击您的项目。您可以看到以下屏幕。
单击身份验证后,您将看到以下屏幕。在此屏幕上,单击“登录方法”选项卡。
单击登录方法后,您将看到下面的身份验证屏幕列表。单击电话选项并启用它。
单击“电话”选项,您将看到以下弹出屏幕。在此屏幕内,单击启用选项并保存。
Note: For getting OTP don’t enter your phone number with country code because we are already adding that country code in our code itself.
输出:
GitHub链接: https : //github.com/ChaitanyaMunje/FirebasePhoneAuthentication