JWT (Json Web Tokens) can be used for user authentication. They are token-based. First, you need to encode the token and send it to the client. Client will save it in his local storage or cookie. In order to decode the token, user must provide the token. Both encode and decode function on JWT wll be performed on server side in PHP.
Or you can download and include it manually in your PHP project.
Encode JWT in PHP
When admin is logged-in, we need to generate his authentication token. First, you need to include the JWT and Key class on top of your file.
require_once "vendor/autoload.php";
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
Following code will generate a JWT using ID.
$jwt_key = "your_secret_key"; // This should be consistent
$issued_at = time();
// $expiry = strtotime("+30 days");
// jwt valid for 30 days (60 seconds * 60 minutes * 24 hours * 30 days)
$expiry = $issued_at + (60 * 60 * 24 * 30);
$payload = [
'iss' => 'https://your-website.com',
'aud' => 'https://your-website.com',
'iat' => $issued_at, // issued at
'nbf' => $issued_at, // not before
'exp' => $expiry, // expiry time
"id" => 1
];
$jwt = JWT::encode($payload, $jwt_key, 'HS256');
Here, we have set the expiry date of this token to 30 days.
iss: Issuer. It tells who issued this token. Usually it is a URL of the server from where the JWT is being generated.
aud: Audience. This tells who can use this token. By providing the URL of your website, you are telling that this token will be valid if it comes from your website only. You can also pass it as an array if you want to allow multiple audience for same token.
iat: It will be a timestamp in seconds since January 01, 1970 00:00:00 UTC.
nbf: The timestamp seconds after which the token can be used. Token provided before this time will not be accepted. We are setting it same as issued time, so you will be able to use it as soon as you generate it.
exp: This will be the timestamp in seconds when the token will be expired. It will also be timestamps seconds since January 01, 1970 00:00:00 UTC. We are setting it’s validity for 30 days.
id: Optional. This is the custom claim that we are attaching with JWT. So when we decode the token, we will get this ID. This ID can be used to check if the user still exists in the database.
Here we are using HS256 algorithm that is used for authentication in JWT. It is a combination of 2 cryptographic methods:
HMAC (Hash-based Message Authentication Code)
SHA-256 (Secure Hash Algorithm 256 bit)
HMAC
HMAC combines cryptographic hash function with a secret key, in this case it will be $jwt_key. It ensures that the token is not been changed and is sent from the owner of secret key (your server).
SHA-256
SHA-256 generates a 256-bit hash from any given value. It is a one-way encryption method. It means that once the hash is generated, it cannot be decrypted back to its original state. So you will not be able to see the original message once it is encrypted.
So in JWT::encode function call, we are sending our payload and secret key. We are also telling the php-jwt library to use the HS256 algorithm. It takes our payload and encrypt it with our secret key and return the hash.
You do not have to save this token in your database. Just return it as a response to AJAX request and user can save it in his local storage.
localStorage.setItem("accessToken", accessToken)
To save the token on user side, we are using localStorage web API. This will keep the access token in local storage until removed using Javascript localStorage.removeItem(“accessToken”) or if the browsing history is deleted. However, it can store only upto 10 MB. But that will be enough in this case. The token generated will be a string of just a few bytes.
It stores the data in key-value pair. In this case, our key is “accessToken” and our value is the accessToken received from server.
Note: The first parameter is a string and second is a variable.
Decode JWT in PHP
Now whenever admin sends an AJAX request, he needs to pass that access token in headers.
Here, we are first creating an AJAX (Asynchronous JavaScript and XML) object. Then we are opening the request with method POST and the server URL is “index.php”, you can write your own route. Third parameter is async, it’s default value is also true. It means that the request will be processed asyncronously. If you use false, it will not return any value until the response is received, thus blocking the UI which is not good for user experience.
After that, we are attaching Authorization header with the AJAX request. It is a good practice to send authorization tokens in header for security and it is also a standardized way of sending tokens. So if you are developing a website or a mobile application, every developer will know that the token needs to be sent in the header.
We are using Bearer authorization token because they hide the sensitive data that we are sending in payload. Thus, even if someone reads the headers, he won’t be able to read the ID of user. And we are fetching the token value from local storage we saved earlier.
Finally, we are sending the request. If you are to send some data with the request too, you can send it in FormData object. Check our tutorial on how to send AJAX request with FormData.
Then on server side, we need to get the access token from Authorization header and decode it to see if it is valid.
// index.php
// Get the JWT from the Authorization header
try
{
$headers = getallheaders(); // returns an array of all headers attached in this request
if (!isset($headers['Authorization']))
{
echo json_encode([
"status" => "error",
"message" => "'authorization' header not present."
]);
exit();
}
$auth_header = $headers['Authorization'];
list($jwt) = sscanf($auth_header, "Bearer %s");
$decoded = JWT::decode($jwt, new Key($jwt_key, 'HS256'));
$id = $decoded->id;
return $id;
}
catch (\Exception $exp)
{
echo json_encode([
"status" => "error",
"message" => $exp->getMessage()
]);
exit();
}
First, we are fetching all the headers from the request. Then we are checking if the Authorization header is present in the request. If not, then we are throwing an error. So if user fails to attach the Authorization header in the request, it will not process further.
sscanf: This function is used to read and parse the value from a string. While “sprintf” is used to only format the data, but this function reads the data and parses as well.
Our format “Bearer %s” tells the function to expecct Bearer at the start of the string. And %s tells it to put the remaining string in a variable.
list() is a built-in function in PHP. It is used to assign multiple values to multiple variables respectively. In this case, we are assigning value of “%s” to $jwt variable.
After that, we are decoding the token. Decode function in JWT PHP is a little different than the encode function. First parameter is the token, second is an instance of Key class from php-jwt library. It also accepts 2 parameters, first is the secret key used to generate the token and second is the algorithm used while generating the token. If there is any mismatch in token, secret key or algorithm, it will throw an exception and we will receive that in catch block.
It will return the payload that we are saving in $decoded variable. From this decoded variable, you can get the ID of the authenticated user.
That’s how you can encode and decode the JWT in PHP. If you face any problem in following this, kindly do let me know.
In the previous tutorial, we created a URL shortener app where user can make their URL short and easily shareable. In this tutorial, we are going to add authentication using JWT (Json Web Token) in Python.
Create a Vuex store
First, we need to create a Vuex store. So run the following command in your “web” folder to install Vuex module:
> npm install vuex
After that, go to your “web/src” folder and create a file named “store.js”. Write the following code in that file.
This will call can AJAX to the Python API to fetch the authenticated user and save them in Vuex store. Now we need to create an API in Python that will handle this request.
Open terminal in your “api” folder and run the following command to install JWT module. It will be used for generating Json Web Tokens.
> pip3 install pyjwt
Open your “api/api.py” file and import this module.
import jwt, time
We will also be needing time module to convert the current time into Unix timestamp. That will be used to expire the JWT after 24 hours.
Then create a variable for JWT secret. It can be any random string.
jwt_secret = "qwertyuiopasdfgfhjklzxcvbnm"
Then create the following API.
@app.post("/me")
def get_user(timezone: Annotated[str, Form()], access_token: Annotated[str, Form()]):
user = None
try:
payload = jwt.decode(access_token, jwt_secret, algorithms = "HS256")
dt1 = time.mktime(datetime.now().timetuple())
dt2 = payload["exp"]
delta = dt2 - dt1
delta = delta / 60 / 60
if delta <= 0:
return {
"status": "error",
"message": "You have been logged-out."
}
user = db["users"].find_one({
"$and": [{
"_id": ObjectId(payload["user_id"])
}, {
"access_token": access_token
}]
})
if user == None:
return {
"status": "error",
"message": "You have been logged-out."
}
return {
"status": "success",
"message": "User has been fetched.",
"user": {
"_id": str(user["_id"]),
"name": user["name"],
"email": user["email"]
}
}
except Exception as error:
return {
"status": "error",
"message": "You have been logged-out.",
"error": str(error)
}
else:
pass
finally:
pass
The API will first decode the JWT. It will return payload containing “user_id” and “exp” in Unix timestamp. “exp” is expiry date of JWT.
Then it takes the difference between current time and the expiry time. Difference “delta” will be in seconds. So we will convert it into hours and check if it is greater than 24.
If JWT is not expired yet, we will check if the user exists using his ID and access token. And return the response to the client.
If you test the app now, and open your browser’s “Network” tab. You will see that right now you are getting “status” as “error”. This is because no user is signed-in yet.
Login/signup
In your AppHeader component, create the following links in navbar.
Then in your “api/api.py”, we need to create an API in Python that will handle this request. We need to encrypt the passwords before storing them in database. So install the bcrypt module in Python.
> pip3 install bcrypt
Then import it in “api/api.py”.
import bcrypt
And then create an API that will save the user’s data in database.
Create a file named “LoginComponent.vue” in your “web/src/components” folder. Open “web/src/main.js” and import the LoginComponent:
import LoginComponent from "./components/LoginComponent.vue"
And add it in “routes” array.
{ path: "/login", component: LoginComponent },
Following will be the content of LoginComponent:
<template>
<div class="container" style="margin-top: 50px;">
<div class="row">
<div class="offset-md-3 col-md-6">
<h2 style="margin-bottom: 30px; text-align: center;">Login</h2>
<form method="POST" v-on:submit.prevent="login">
<div class="form-group">
<label>Enter email</label>
<input type="email" class="form-control" name="email" required />
</div>
<br />
<div class="form-group">
<label>Enter password</label>
<input type="password" class="form-control" name="password" required />
</div>
<br />
<input type="submit" v-bind:value="isLoading ? 'Loading...' : 'Login'" v-bind:disabled="isLoading" name="submit" class="btn btn-primary" />
</form>
</div>
</div>
</div>
</template>
<script>
import axios from "axios"
import swal from "sweetalert2"
import store from "../store"
export default {
name: "LoginComponent",
methods: {
login: async function () {
const form = event.target;
const formData = new FormData(form);
this.isLoading = true;
try {
const response = await axios.post(
this.$api_url + "/login",
formData
)
if (response.data.status == "success") {
// get access token from server
const access_token = response.data.access_token
// save in local storage
localStorage.setItem(this.$access_token_key, access_token)
store.commit("set_user", response.data.user)
form.reset()
// to go to home page without refreshing
this.$router.push("/")
} else {
swal.fire("Error", response.data.message, "error")
}
} catch (exp) {
console.log(exp)
} finally {
this.isLoading = false
}
}
}
}
</script>
Once user is logged-in, we will save the access token in local storage and redirect the user to home page. In your main.js file, create a variable that will hold the key for local storage value.
It will first check if the email exists. Then it will check the password against the hashed password saved in database. Then it will generate an access token using algorithm “HS256”.
Test the app now. You will be able to login now. And once logged-in, you will no longer see login/signup links in the navbar. Instead, you will see a button for logout.
Logout
Logout button in navbar already have an onclick listener attached to it. We need to create its method in AppHeader component.
It simply removes the “access_token” key from that user’s Mongo DB document. Try to logout now, you will be redirected to login page and you will again see the login/signup links in the navbar.
So that’s how you can do the user authentication in Python using JWT.
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:
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.
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:
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.
This tutorial will discuss how you can create a JWT authentication system (Login, Registration, and Logout) using JSON Web Token in Node JS and Mongo DB. You can follow the video below if you prefer a video tutorial:
First, make sure you have downloaded and installed Node JS and Mongo DB. You can also download Mongo DB Compass to view the database.
Setup the Project
First, create an empty folder anywhere on your computer and open the command prompt in it. Once CMD is open inside the folder, run the following command:
express: A framework used for better routing, middleware etc.
express-formidable: To get the values from AJAX.
mongodb: To interact with database.
http: To handle HTTP requests.
bcrypt: To encrypt and decrypt the password.
jsonwebtoken: To generate JSON Web Token used for authentication.
ejs: View engine to display HTML pages.
Now, create a file named “server.js” at the root of your folder. To start the server you can use the following command:
node server.js
But every time you made some changes in the server.js file, you have to run that command again. To prevent this, you can install the nodemon module using the following command:
npm install -g nodemon
Then you can use the following command to keep the server running:
nodemon server.js
Start the Server
Open your server.js file and write the following code in it:
// include express module
var express = require("express");
// create instance of express
var app = express();
// use express-formidable middleware
var formidable = require("express-formidable");
app.use(formidable());
// include mongodb module
var mongodb = require("mongodb");
// get mongodb client
var mongoClient = mongodb.MongoClient;
// get ObjectId, it is unique for each document
var ObjectId = mongodb.ObjectId;
// create http server from express instance
var http = require("http").createServer(app);
// include bcrypt module
var bcrypt = require("bcrypt");
// include jsonwebtoken module
var jwt = require("jsonwebtoken");
// random secret string
var accessTokenSecret = "myAccessTokenSecret1234567890";
// use public folder for css and js files
app.use(express.static(__dirname + "public"));
// use ejs engine to render html files
app.set("view engine", "ejs");
var mainURL = "http://localhost:3000";
// start the server at port 3000
http.listen(3000, function () {
console.log("Server started.");
// connect with mongodb
mongoClient.connect("mongodb://localhost:27017", function (error, client) {
// database name will be "jwt_authentication"
var database = client.db("jwt_authentication");
console.log("Database connected");
});
});
This will include all the necessary modules and start the server at port 3000. The module used for JWT authentication is named jsonwebtoken. You can access it from your browser with the following link:
http://localhost:3000/
You will see an error because there isn’t any route for the home page. Open your CMD and you will see 2 messages:
“Server started.”
“Database connected”
If you open the Mongo DB Compass you will not see a database. Because database will be created only there is at least one collection in it. So our database will be created when there is at least one user in our database.
User Registration
Go to the following address in your browser:
http://localhost:3000/signup
First, we are going to create a route in our server.js right after the database is connected.
server.js
// route for signup requests
app.route("/signup")
// get request accessed from browser
.get(function (request, result) {
// render signup.ejs file inside "views" folder
result.render("signup");
});
Now we need to create a folder named views at our root folder. Inside this folder, create a file named signup.ejs (note the extension). Also create 2 more files, header.ejs and footer.ejs.
header.ejs
<!-- menu items will be created using Javascript -->
<ul id="main-menu">
</ul>
<script>
// variables used in all files
var mainURL = "http://localhost:3000";
var accessTokenKey = "accessToken";
var user = null;
</script>
<script>
function doRegister(form) {
// disable the submit button and show "Loading..." text
form.submit.setAttribute("disabled", "disabled");
form.submit.value = "Loading...";
// create AJAX object
var ajax = new XMLHttpRequest();
// 1. method is POST
// 2. path where request will be sent
// 3. request will be asynchronous
ajax.open("POST", mainURL + "/signup", true);
// called everytime status of request changes
ajax.onreadystatechange = function () {
// when response is received from server
if (this.readyState == 4) {
// if the request is OK
if (this.status == 200) {
// response received from server
console.log(this.responseText);
// enable the submit button
form.submit.removeAttribute("disabled");
form.submit.value = "Register";
// convert the JSON string into Javascript object
var response = JSON.parse(this.responseText);
// display message
alert(response.message);
// if the user is created, then redirect to login
if (response.status == "success") {
window.location.href = "/login";
}
}
// if there is an internal server error
if (this.status == 500) {
console.log(this.responseText);
}
}
};
// create form data object from form
var formData = new FormData(form);
// actually sending the AJAX request
ajax.send(formData);
// prevent the form from submitting
return false;
}
</script>
This will show a form with input fields for name, email and password. Now we need to create a POST route in our server.js. We will chain the POST route after our “/signup” GET route.
// route for signup requests
app.route("/signup")
// get request accessed from browser
.get(function (request, result) {
// render signup.ejs file inside "views" folder
result.render("signup");
})
// post request called from AJAX
.post(async function (request, result) {
// get values from signup form
var name = request.fields.name;
var email = request.fields.email;
var password = request.fields.password;
// check if email already exists
var user = await database.collection("users").findOne({
"email": email
});
if (user != null) {
result.json({
"status": "error",
"message": "Email already exists."
});
return true;
}
// encrypt the password
bcrypt.hash(password, 10, async function (error, hash) {
// insert in database
await database.collection("users").insertOne({
"name": name,
"email": email,
"password": hash,
"accessToken": ""
});
// send the response back to client
result.json({
"status": "success",
"message": "Signed up successfully. You can login now."
});
});
});
If you run the code now, you will see a registration form. You can enter your name, email, and password and hit enter. The first time, you will see a success message and you will be redirected to the login route. You can refresh your Mongo DB Compass, and you will see your database and one collection of “users”. Inside this collection, you will see your document inserted. If you enter the same email again, you will get an error.
User Login – JWT authentication
Go to the following address in your browser:
http://localhost:3000/login
First, we are going to create a route in our server.js right after the signup route.
server.js
// route for login requests
app.route("/login")
// get request accessed from browser
.get(function (request, result) {
// render login.ejs file inside "views" folder
result.render("login");
});
Then create a file named login.ejs and write the following code in it:
<script>
function doLogin(form) {
// disable the submit button and show "Loading..." text
form.submit.setAttribute("disabled", "disabled");
form.submit.value = "Loading...";
// create AJAX object
var ajax = new XMLHttpRequest();
// 1. method is POST
// 2. path where request will be sent
// 3. request will be asynchronous
ajax.open("POST", mainURL + "/login", true);
// called everytime status of request changes
ajax.onreadystatechange = function () {
// when response is received from server
if (this.readyState == 4) {
// if the request is OK
if (this.status == 200) {
// response received from server
console.log(this.responseText);
// enable the submit button
form.submit.removeAttribute("disabled");
form.submit.value = "Login";
// convert the JSON string into Javascript object
var response = JSON.parse(this.responseText);
// if user is logged in successfully
if (response.status == "success") {
// get access token from server
var accessToken = response.accessToken;
// save in local storage
localStorage.setItem("accessToken", accessToken);
// redirect to home page
window.location.href = "/";
} else {
// display message
alert(response.message);
}
}
// if there is an internal server error
if (this.status == 500) {
console.log(this.responseText);
}
}
};
// create form data object from form
var formData = new FormData(form);
// actually sending the AJAX request
ajax.send(formData);
// prevent the form from submitting
return false;
}
</script>
This will show a form with input fields for email and password. Now we need to create a POST route in our server.js. We will chain the POST route after our “/login” GET route.
// route for login requests
app.route("/login")
// get request accessed from browser
.get(function (request, result) {
// render login.ejs file inside "views" folder
result.render("login");
})
// post request called from AJAX
.post(async function (request, result) {
// get values from login form
var email = request.fields.email;
var password = request.fields.password;
// check if email exists
var user = await database.collection("users").findOne({
"email": email
});
if (user == null) {
result.json({
"status": "error",
"message": "Email does not exists."
});
return false;
}
// check if password is correct
bcrypt.compare(password, user.password, async function (error, isVerify) {
if (isVerify) {
// generate JWT of user
var accessToken = jwt.sign({
"email": email
}, accessTokenSecret);
// update JWT of user in database
await database.collection("users").findOneAndUpdate({
"email": email
}, {
$set: {
"accessToken": accessToken
}
});
result.json({
"status": "success",
"message": "Login successfully.",
"accessToken": accessToken
});
return false;
}
result.json({
"status": "error",
"message": "Password is not correct."
});
});
});
If you run the code now, you will see a login form. You can enter your email and password and hit enter. If the credentials are correct, then it will save the access token in your local storage in your browser, and you will be redirected to the home page. You can refresh your Mongo DB Compass, and you will see that the accessToken field of the user has been updated. If you enter the wrong credentials, then it will not update the database.
Home Page
Now we need to create a route for our home page in server.js:
// route for home page
app.get("/", function (request, result) {
result.render("index");
});
Create a file named index.ejs inside views folder and write the following code in it:
<%- include ("header") %>
<%- include ("footer") %>
Now comes the footer part. Following will be the code of your footer.ejs file:
footer.ejs
<script>
// get user on page load
window.addEventListener("load", function () {
getUser();
});
function getUser() {
// check if user is logged in
if (localStorage.getItem(accessTokenKey)) {
// call AJAX to get user data
var ajax = new XMLHttpRequest();
ajax.open("POST", mainURL + "/getUser", true);
ajax.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
// console.log(this.responseText);
var response = JSON.parse(this.responseText);
if (response.status == "success") {
// user is logged in
window.user = response.user;
} else {
// user is logged out
localStorage.removeItem(accessTokenKey);
}
showMainMenu();
}
if (this.status == 500) {
console.log(this.responseText);
}
}
};
var formData = new FormData();
formData.append("accessToken", localStorage.getItem(accessTokenKey));
ajax.send(formData);
return false;
}
showMainMenu();
}
function doLogout() {
// send beacon to server before redirecting
var formData = new FormData();
formData.append("accessToken", localStorage.getItem(accessTokenKey));
navigator.sendBeacon(mainURL + "/logout", formData);
// remove access token from local storage
localStorage.removeItem(accessTokenKey);
return true;
}
function showMainMenu() {
var html = "";
// if user is logged in
if (localStorage.getItem(accessTokenKey)) {
html += `<li>
<a href='/login' onclick='return doLogout();'>Logout</a>
</li>`;
} else {
html += `<li>
<a href='/login'>Login</a>
</li>`;
html += `<li>
<a href='/signup'>Signup</a>
</li>`;
}
// show in main menu
document.getElementById("main-menu").innerHTML = html;
}
</script>
This will show login and signup links if the user is not logged in. If the user is logged in, then it will display a logout button. When the logout button is clicked, it will be redirected to the “/login” route. But before redirecting, it will send a beacon to the server to empty the accessToken field in the database. So we need to create POST routes for “/getUser” and for “/logout”:
// return user data using access token
app.post("/getUser", async function (request, result) {
var accessToken = request.fields.accessToken;
var user = await database.collection("users").findOne({
"accessToken": accessToken
});
if (user == null) {
result.json({
"status": "error",
"message": "User has been logged out. Please login again."
});
return false;
}
result.json({
"status": "success",
"message": "Data has been fetched.",
"user": user
});
});
// empty the access token of user (logout)
app.post("/logout", async function (request, result) {
var accessToken = request.fields.accessToken;
await database.collection("users").findOneAndUpdate({
"accessToken": accessToken
}, {
$set: {
"accessToken": ""
}
});
result.json({
"status": "success",
"message": "User has been logged out."
});
});
With that, your authentication is completed. You can log in and log out now. Once you log out and refresh the Mongo DB Compass, you will see the accessToken field becomes empty. And it will again have the value once the user logged in again.
Why we used Beacon ?
You might have noticed that we have used Beacon instead of AJAX when the logout button is clicked. The reason for this is when the browser navigates from one page to another, the AJAX calls are sometimes aborted by the browser. To prevent this, we use beacons.
Get Data using AJAX
Now that your authentication system is done, you might want to show data to logged-in users only. So for example, you have a blogging website and you want to show your blog posts to logged-in users only. So you need to do the following steps.
1) Create Variable and a Function
In the file where you want to fetch and display the data, create the following variable and a function in Javascript.
<script>
var onPostsPage = true;
function getPosts() {
// call ajax
}
</script>
If you want to learn how to call an AJAX request and show data from it, follow this tutorial.
2) Call Function if Variable is Set
In your footer.ejs, when the user is logged-in, check if this variable is set and is true. If yes, then simply call that function.
// user is logged in
window.user = response.user;
if (typeof onPostsPage !== "undefined" && onPostsPage) {
getPosts();
}
So, that’s how you can create a JWT authentication system In Node JS and Mongo DB.