Firebase Authentication In Android
Authentication is the process to provide uniqueness to each user of your application. It will be the identity of particular user.
If your application requires user’s data to be securely stored, you need to authenticate each and every user.
In earlier days we need to have some back-end service developed either in PHP, Java or some other platform. We need some web developer to do that kind of things.
Firebase Authentication provides a way to directly authenticate a user via email and password and store that user to cloud.
Firebase Authentication also support social media authentication like G+, Facebook, Twitter, Github. It means now its a easy task to perform login with facebook or login with g+ task.
Types of Authentication Firebase supports :
- Email and password based authentication – Authentication with email and password
- Federated identity provider integration – Authentication with social media(G+, Facebook etc)
- Custom auth system integration
- Anonymous auth – Creates an anonymous account.
In today’s post we will see how basic authentication works.
Setup Firebase Authentication
Step 1 : Create a new project on Firebase Console. Enter you project name and select country, than click CREATE PROJECT
Step 2 : After creation of project click on Add Firebase to your Android app. Enter package name, App nickname(optional) and SHA-1 key(optional) and click on ADD APP.
Step 3 : You will receive google-services.json file, put it inside app/ folder of your project.
Step 4 : Add dependency to your root level build.gradle file.
1 2 3 4 |
dependencies { ... classpath 'com.google.gms:google-services:3.0.0' } |
Step 5 : Add dependency to your app/module level build.gradle file.
1 2 3 4 |
dependencies { ... compile 'com.google.firebase:firebase-auth:10.2.0' } |
Step 6 : Add plugin at the bottom of your app-level build.gradle file.
1 |
apply plugin: 'com.google.gms.google-services' |
Step 7 : That’s it, sync your project to apply all these effect of dependencies.
Code
Initialize FirebaseAuth in your Activity or Application class.
1 2 3 4 5 6 7 |
private FirebaseAuth mFirebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { .... mFirebaseAuth = FirebaseAuth.getInstance(); } |
Register a User
1 2 3 4 5 6 7 8 9 10 11 |
mFirebaseAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Toast.makeText(RegisterActivity.this, "User registered successfully", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); |
Login a User
1 2 3 4 5 6 7 8 9 10 11 12 |
mFirebaseAuth.signInWithEmailAndPassword(email,password) .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ Toast.makeText(LoginActivity.this, "Logged in successfully", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); |
You can get current user object either from Task or by using FirebaseAuth object
1 2 3 4 5 6 7 8 |
@Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ FirebaseUser firebaseUser = task.getResult().getUser(); //or FirebaseUser firebaseUser = mFirebaseAuth.getCurrentUser(); } } |
Change Password
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
firebaseUser.updatePassword(password) .addOnCompleteListener(ChangePasswordActivity.this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(ChangePasswordActivity.this, "Password changed successfully", Toast.LENGTH_SHORT).show(); return; } if(task.getException() instanceof FirebaseAuthRecentLoginRequiredException){ //you need to reauthenticate user in order to change the password. //user might have logged in before a while, and firebase is not able to authenticate that user. } } }); |
Reset Password
1 2 3 4 5 6 7 8 9 10 11 12 |
mFirebaseAuth.sendPasswordResetEmail(email) .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(LoginActivity.this, "An email has been sent.", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); |
Update Current User Profile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
UserProfileChangeRequest userProfileChangeRequest = new UserProfileChangeRequest.Builder() .setDisplayName(display name) .setPhotoUri(Uri.parse(photo uri)) .build(); firebaseUser.updateProfile(userProfileChangeRequest) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(ProfileActivity.this, "Profile updated.", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(ProfileActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); |
Logout User
1 |
mFirebaseAuth.signOut(); |
Isn’t it looks so easy? Yes it is, have your own application with authentication and that also without having help of web developer or any heavy servers.
Ravi Rupareliya
Latest posts by Ravi Rupareliya (see all)
- Dialogflow Entities With Actions on Google - May 7, 2020
- Actions on Google Using Cloud Functions - February 3, 2020
- Create WhatsApp Stickers Android Application - April 19, 2019