Login with JWT – Kotlin, Node JS, Mongo DB

In this tutorial, we will teach you how you can login a user with JWT (JSON Web Token) in the android app using Kotlin and Node JS. We will be using Node JS to generate JWT and Mongo DB to save it.

Creating an activity

First, we will create an empty activity named “LoginActivity.kt”. Following will be the code of that file:

package com.adnantech.myapp

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class LoginActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
    }
}

This will look for a file named “activity_login.xml” inside the “res/layout” folder.

Create an XML file

Then we will create a file named “activity_login.xml” inside the “res/layout” folder. That file will have the following code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    tools:context=".LoginActivity">

    <TextView
        android:id="@+id/heading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:textAlignment="center"
        android:textSize="40sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/etPhone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/heading"
        android:layout_marginTop="20dp"
        android:hint="Enter phone"
        android:inputType="phone" />

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etPhone"
        android:layout_marginTop="20dp"
        android:hint="Enter password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etPassword"
        android:layout_marginTop="20dp"
        android:text="Login" />

</RelativeLayout>

It will display the heading “Login” horizontally center-aligned. Two input fields. One to enter the phone number, and one for the password. It will also display a button that when clicked will call an HTTP request to authenticate the user.

Button onclick event listener

We need to attach an “onclick” event listener to the button. So we will create instances of all our input fields and button.

class LoginActivity : AppCompatActivity() {

    private lateinit var etPhone: EditText
    private lateinit var etPassword: EditText
    private lateinit var btnLogin: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        etPhone = findViewById(R.id.etPhone)
        etPassword = findViewById(R.id.etPassword)
        btnLogin = findViewById(R.id.btnLogin)

        btnLogin.setOnClickListener {
            doLogin()
        }
    }

    private fun doLogin() {
        // [HTTP request to authenticate the user]
    }
}

And inside this button click listener, we are calling our method that will call an HTTP request.

Calling an HTTP request

To call an HTTP request, first, make sure you have INTERNET and ACCESS_NETWORK_STATE permissions added in your “AndroidManifest.xml” file.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

Then you need to add the following line in your “app/build.gradle” file:

implementation "com.android.volley:volley:1.2.1"

Make sure to “Gradle sync” after pasting that line. You will see the option to sync Gradle on top in Android studio. After that, you need to write the following code in the [HTTP request to authenticate the user] section:

btnLogin.isEnabled = false

val queue = Volley.newRequestQueue(this)
val url = "http://172.20.10.4:3000/login"

val requestBody =
    "phone=" + URLEncoder.encode(
        etPhone.text.toString(),
        "UTF-8"
    ) + "&password=" + etPassword.text
val stringReq: StringRequest =
    object : StringRequest(
        Method.POST, url,
        Response.Listener { response ->
            btnLogin.isEnabled = true
            Log.i("mylog", response)
        },
        Response.ErrorListener { error ->
            Log.i("myLog", "error = " + error)
        }
    ) {
        override fun getBody(): ByteArray {
            return requestBody.toByteArray(Charset.defaultCharset())
        }
    }
queue.add(stringReq)

This will first disable the login button. Then it will create an instance of Volley. After that, it sets the path of an API. You can get your IP address by running either of the following commands in your terminal:

> ipconfig /all
or
> ifconfig

You need to copy the ipv4 address and paste it as your IP address.

Then it creates a request body, the parameters that will be sent to the API. Creates an instance of “StringRequest”. When the response is received, it simply enables the login button and displays the response in the log. You can view the response by opening your “logcat” in your android studio bottom bar. And select “info” and search for “mylog”.

If you want to convert the JSON string into Kotlin class, you can check out this tutorial.

We have already created a public GitHub repo for the authentication API. You can check it out here.

So that’s how you can create a login activity in android using Kotlin with Node JS and Mongo DB as the backend. If you face any problem in following this, kindly do let me know.

Leave a Reply

Your email address will not be published. Required fields are marked *