JWT - JSON Web Tokens
In this project tutorial we will use the JWT or JSON Web Tokens to fetch data from the server.
In the previous tutorial we learned how to generate and validate JWT. Feel free to check that out.
Open the script.js file we created in the introduction tutorial.
We will call the user validation API.
API: http://localhost/jwt-php-project/api/user
METHOD: POST
DATA: {
"email": {email},
"password": {password}
}
On success we will get the following response from the server.
{
"code": 200,
"status": "success",
"message": "Valid login credentials.",
"userid": "u1",
"jwt": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyaWQiOiJ1MSIsImlhdCI6MTUyMzgwMTA3OSwiZXhwIjoxNTIzODAxMTM5fQ.ProXLhQbSEqfwj3DAqdJQSJmT8q2JgAw_uJP3BgiSmg"
}
To validate the user login credentials we will write the following simple jQuery code.
$('#login').on('submit', function (e) {
// login
$.ajax({
url: './api/user',
type: 'POST',
data: JSON.stringify({
email: $('#login-email').val(),
password: $('#login-password').val()
}),
success: function (data) {
var html = "<pre>" + JSON.stringify(data, null, 2) + "</pre>" +
"<hr>" +
"<button class='btn btn-primary' id='getuser' data-jwt='" + data.jwt + "'>Get User Detail</button>" +
"<hr>" +
"<div id='detail-container'></div>";
$('#result-container').html(html);
$('#login')[0].reset();
},
error: function () {
}
});
return false;
});
In the above code we are listening to the login form submit event.
On form submission we are taking the email address and password provided by the user and then calling the API for validation.
If the entered details are correct then we will get a success reponse.
The above success response hold the jwt
generated for the provided user login credential.
We will use this JWT value to fetch the user detail.
Note! We also have the Get User Detail button which when clicked will give use the user detail by calling the API with the generated JWT.
For this we will call the get user detail API.
API: http://localhost/jwt-php-project/api/user
METHOD: GET
PARAMETER: jwt={jwt}
If the jwt
value passed to the server is valid then we will get back the following response.
{
"code": 200,
"status": "success",
"data": {
"userid": "u1",
"email": "yusufshakeel@example.com",
"firstname": "Yusuf",
"lastname": "Shakeel"
},
"jwt_payload": {
"userid": "u1",
"iat": 1523801079,
"exp": 1523801139
}
}
So, to get the user details we will write the following code that will fire on button click.
$('body').on('click', '#getuser', function (e) {
var jwt = $(this).attr('data-jwt');
// get user detail
$.ajax({
url: './api/user',
type: 'GET',
data: {
jwt: jwt
},
success: function (data) {
if (data.status === 'success') {
var lifespan = Number(data.jwt_payload.exp - data.jwt_payload.iat); // in ms
var html = "<p>For this demo JWT will expire after " + lifespan + " seconds.</p>" +
"<pre>" + JSON.stringify(data, null, 2) + "</pre>";
$('#detail-container').html(html);
setTimeout(function () {
$('#detail-container').html('<p>JWT expired!</p>');
}, lifespan * 1000);
} else {
var html = "<pre>" + JSON.stringify(data, null, 2) + "</pre>";
$('#detail-container').html(html);
}
},
error: function () {
}
});
});
On success we will get back the following response from the server.
Note! For this demo project the JWT is set to expire after 60 seconds.
So, after expiry we will see the following message.
And after expiry if we try to click the "Get User Detail" button to fetch the user detail we will get invalid JWT message.
You will find the complete code here.
Alright guys, this brings us to the end of this project tutorial. Share this tutorial if you find it helpful.
You can download the complete project code from my GitHub repository jwt-php-project.
Thanks for reading. See you in the next tutorial.
Have fun coding :-)
ADVERTISEMENT