Authentication is one of the essential elements in modern mobile applications. User-driven authentication is crucial for security and privacy. In this course, we will explain in detail how to implement authentication features in Android applications using Kotlin.
1. What is Authentication Functionality?
The authentication functionality refers to the process of verifying a user’s identity and allowing only legitimate users to access specific features of the application. For example, a system that enables users to create accounts and log in falls under this category. The authentication process typically involves the following steps:
- Sign Up
- Login
- Logout
- Password Reset
2. Project Setup
Create a new project using Android Studio. Here, we will cover only the basic settings:
- Open Android Studio.
- Click ‘Start a new Android Studio project’.
- Select ‘Empty Activity’ and click ‘Next’.
- Enter the project name and select ‘Kotlin’ as the language.
- Finally, click Finish to create the project.
3. Adding Dependencies
We will use Firebase Authentication to implement the authentication functionality. Using Firebase makes it easy to implement authentication with email and password.
Add the following dependency to the project’s build.gradle(:app)
file:
implementation 'com.google.firebase:firebase-auth-ktx:21.0.1'
Then, set up Firebase in your project.
- Log in to the Firebase console and create a new project.
- Enable the Firebase Authentication service.
- Activate the email/password authentication method.
- Download the google-services.json file and add it to the app directory.
4. Creating Layouts
Create the layouts for the login and signup screens in XML. Create activity_login.xml
and activity_signup.xml
files.
activity_login.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/emailEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"/>
<EditText
android:id="@+id/passwordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"/>
<Button
android:id="@+id/loginButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"/>
</LinearLayout>
activity_signup.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/signupEmailEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"/>
<EditText
android:id="@+id/signupPasswordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"/>
<Button
android:id="@+id/signupButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sign Up"/>
</LinearLayout>
5. Code Implementation
Now, we will implement login and signup functionality in the Android application.
LoginActivity.kt
package com.example.authentication
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
class LoginActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var emailEditText: EditText
private lateinit var passwordEditText: EditText
private lateinit var loginButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
auth = FirebaseAuth.getInstance()
emailEditText = findViewById(R.id.emailEditText)
passwordEditText = findViewById(R.id.passwordEditText)
loginButton = findViewById(R.id.loginButton)
loginButton.setOnClickListener {
login()
}
}
private fun login() {
val email = emailEditText.text.toString()
val password = passwordEditText.text.toString()
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "Please enter email and password.", Toast.LENGTH_SHORT).show()
return
}
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Toast.makeText(this, "Login Successful", Toast.LENGTH_SHORT).show()
startActivity(Intent(this, MainActivity::class.java))
} else {
Toast.makeText(this, "Login Failed: ${task.exception?.message}", Toast.LENGTH_SHORT).show()
}
}
}
}
SignupActivity.kt
package com.example.authentication
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
class SignupActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var signupEmailEditText: EditText
private lateinit var signupPasswordEditText: EditText
private lateinit var signupButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_signup)
auth = FirebaseAuth.getInstance()
signupEmailEditText = findViewById(R.id.signupEmailEditText)
signupPasswordEditText = findViewById(R.id.signupPasswordEditText)
signupButton = findViewById(R.id.signupButton)
signupButton.setOnClickListener {
signup()
}
}
private fun signup() {
val email = signupEmailEditText.text.toString()
val password = signupPasswordEditText.text.toString()
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "Please enter email and password.", Toast.LENGTH_SHORT).show()
return
}
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Toast.makeText(this, "Signup Successful", Toast.LENGTH_SHORT).show()
startActivity(Intent(this, LoginActivity::class.java))
} else {
Toast.makeText(this, "Signup Failed: ${task.exception?.message}", Toast.LENGTH_SHORT).show()
}
}
}
}
6. Implementing Password Reset Functionality
You can add functionality that allows users to reset their passwords in case they forget them. This functionality is done by sending a password reset link to the registered email.
PasswordResetActivity.kt
package com.example.authentication
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
class PasswordResetActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var emailEditText: EditText
private lateinit var resetButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_password_reset)
auth = FirebaseAuth.getInstance()
emailEditText = findViewById(R.id.emailEditText)
resetButton = findViewById(R.id.resetButton)
resetButton.setOnClickListener {
resetPassword()
}
}
private fun resetPassword() {
val email = emailEditText.text.toString()
if (email.isEmpty()) {
Toast.makeText(this, "Please enter your email.", Toast.LENGTH_SHORT).show()
return
}
auth.sendPasswordResetEmail(email)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Toast.makeText(this, "Password reset link has been sent.", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Failed to send: ${task.exception?.message}", Toast.LENGTH_SHORT).show()
}
}
}
}
7. Optimization and Security
It is advisable to follow certain recommendations to protect data in authentication functionality:
- Always store passwords securely. Firebase encrypts passwords for storage.
- Use HTTPS to protect data transmission.
- Maintain user login status securely through session management.
- Identify and resolve vulnerabilities through security audits and reviews.
8. Conclusion
In this course, we explored how to implement authentication features using Firebase Authentication with Kotlin. Through this, we were able to implement user registration, login, and password reset functionalities. This example is useful for structuring a basic authentication process when developing real applications. You can add more features to build a more robust user authentication system.
Now you have learned how to integrate authentication functionality into Android applications using Kotlin. The next step could be to integrate other authentication methods, such as Google OAuth or Facebook login.