In web development, knowing authorization and authentication mechanisms is essential for developers to understand. The popular methods to handle this procedure are JSON Web Tokens (JWT) and cookie storage.
This post will review the definitions, structures, advantages, and disadvantages of JWT and cookie storage. Finally, we will compare the two to help you decide which is best for your project.
A JWT is a proposed standard for making data with a signature and/or encryption that holds JSON with claims. The tokens are signed using a secret (with the HMAC algorithm) or a public/private key using RSA or ECDSA.
A well-compacted formed JSON Web Token consists of three concatenated Base64url-encoded strings, separated by dots (.):
1{
2 "alg": "HS256",
3 "typ": "JWT"
4}
The JWT payload: The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims:
Private claims: These are the custom claims created to share information between parties that agree on using them and are not registered as public claims.
for example, the payload could be like this;
1{
2 "sub": "1234567890",
3 "name": "user",
4 "admin": true
5}
1HMACSHA256(
2 base64UrlEncode(header) + "." +
3 base64UrlEncode(payload),
4 secret)
The output can be easily passed into an HTML or HTTP environment.
A typical JWT appears as follows:
1eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6ImV4YW1wbGVfdXNlciIsImlhdCI6MTUxNjIzOTAyMn0.eAuqcdegpATdo_fsYMBjJZAGi7hEa_Qba_RDvFnBKSI
Here are some scenarios where JSON Web Tokens are useful:
The main use of JWT is authentication. As long as valid users are still logged into their respective platforms and each API request doesn't demand continuous credential verification, users don't have to constantly verify their identities for every API call because services offer tokens with user data upon login.
The above image process is explained below; 1. The client requests authorization to the authorization server. This is always performed through different authorization flows. 2. When the authorization is granted, the authorization server returns a web token to the client's applications. 3. The application uses the web token to access protected resources or information (like an API).
This section explains the code implementation of how to set JWT on your website. This can be done with several languages of your choice.
The code used here is for the PHP language.
1// Including the dependencies
2require_once 'clients/autoload.php';
3
4use \Firebase\JWT\JWT;
5
6// Your secret key to sign the token
7$secretKey = 'secret_key_here';
8
9// Payload for the token, containing any data you want to include or share
10$payload = array(
11 "user_id" => 123,
12 "username" => "example_user",
13 "exp" => time() + (60 * 60 * 24) // Expiration time, 1 day from now
14);
15
16// Generating the JWT to your clients
17$token = JWT::encode($payload, $secretKey, 'HS256');
18
19echo $token;
The above code is explained below
require_once 'clients/autoload.php';
: This line of code is to include the autoloader file from the installed dependencies which is the Firebase/JWT
library.use \Firebase\JWT\JWT;
: This line of code allows the import of the JWT class from the Firebase JWT library
.
$secretKey = 'your_secret_key_here';
: This variable is to store the secret key used to sign JWT.
$payload = array(...);
: This array contains the claims you want to include in the JWT. This might include the above claims in the example or more. The exp
claim is set for 24 which means the Token
will expire in 24 hours.
1// Generating the JWT to your clients
2$token = JWT::encode($payload, $secretKey, 'HS256');
$token = JWT::encode($payload, $secretKey, 'HS256');
: This line of code generates the Token
using the encode
method of the JWT class. $payload
: The claims to be included.$secretKey
: The secret key used to sign the JWT.'HS256'
: This is the widely used and secure algorithm used for signing the JWT.echo $token
: This code is to output the JWT generated to the screen which can be used for subsequent Authentication and data exchange.> Debugger: Jwt.io
In the Best practice, users should therefore heed to recommended guidelines that listed below:
We would look at the pros and cons of using JSON web tokens in your web application;
There are benefits to using JWTs.
Cross-Origin Resource Sharing (CORS): JWTs in HTTP headers make web apps communicate securely across different origins.
However, several downsides must be considered before adopting JWT fully: 1. Cookie Size Factor: This will cause an increase in the payload size, the size of JWT is larger than the session token and this may negatively impact system performance as a whole. 2. Revocable Tokens: Absence of revocation capabilities necessitates either short lifespans prone to frequent refreshes or employing external blacklist registries imposing extra infrastructure costs 3. Security risk: It is vulnerable to XSS attacks unless adequately protected, especially given increased surface areas exposed via single-page applications (SPA) 4. Limited Token Updates: JWTs are usually unchangeable once issued. If a user’s role or permissions change, they might have to log in again to get an updated token.
In this section, we will understand what cookie storage is, how it works, and its types, including best practices.
This was introduced first by the Netscape Communications Corporation in 1994.
In every visit to some websites, sites serve "Set-Cookie" headers telling the user's or client browser to save given name-value pairs and optional features that indicate duration. This indicates how long a cookie can persist and under what condition it should be sent to the server. This action allows websites to track user's experiences, preferences, and sessions. In essence 'Set-Cookies' headers are the mechanism by which the website communicates with your browser.
Cookies (also known as browser cookies, HTTP cookies or cookies) are small pieces of information sent back to the user's web browser. They are typically used for Authentication, tracking and personalization.
Cookies storage is a client-side storage where client data are stored.
To view Cookies: F12 → ‘Application’ → ‘Storage’ → ‘Cookies’
These are the primary types of cookies:
Cookies are convenient, but they come with inherent hazards:
That could lead to the leakage of sensitive data and unauthorized manipulation because it can be accessed by unauthorised parties. It's critical to understand authorization and authentication while developing and using cookie storage in any modern website.
It can also be used to track users' behaviours across multiple websites or web browsers, which can result in privacy concerns.
Also, cookies are code written by the developer to perform some functions on their webpage. Below we have a basic code written in Javascript for cookie storage;
1<!doctype html>
2<html>
3 <head>
4 <script>
5 function setCookie(cname, cvalue, exdays) {
6 const d = new Date();
7 d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
8 let expires = "expires=" + d.toUTCString();
9 document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
10 }
11
12 function getCookie(cname) {
13 let name = cname + "=";
14 let decodedCookie = decodeURIComponent(document.cookie);
15 let ca = decodedCookie.split(";");
16 for (let i = 0; i < ca.length; i++) {
17 let c = ca[i];
18 while (c.charAt(0) == " ") {
19 c = c.substring(1);
20 }
21 if (c.indexOf(name) == 0) {
22 return c.substring(name.length, c.length);
23 }
24 }
25 return "";
26 }
27
28 function checkCookie() {
29 let user = getCookie("username");
30 if (user != "") {
31 alert("Welcome again " + user);
32 } else {
33 user = prompt("Please enter your name:", "");
34 if (user != "" && user != null) {
35 setCookie("username", user, 30);
36 }
37 }
38 }
39 </script>
40 </head>
41
42 <body onload="checkCookie()"></body>
43</html>
The above code provides three functions
:
1. setCookie(cname,cvalue,exdays)
: This function sets a cookie by taking the name, the value and the number of days it will take to expire.
2. getCookie(cname)
: This retrieves the value of a specific cookie if exists if not it returns empty.
3. checkCookie()
: This will check if a cookie is set, if a cookie is set it displays a response set by the developer, if not, a prompt box might display asking for the name of the user and store the cookie according to the days set in setCookies
function.
Note: Modifications are allowed according to the information of the client you want to store or collect.
Below should be the result:
When using cookies on a website, there are best practices to follow that can help to ensure that they are used effectively.
Let's dive into the comparison between the JWT and Cookies storage, with this we will check out the similarities if there are any, and the differences, choosing between the two for authentication or authorization because both JWT and Cookies can be used for Authorization.
Authorization are typically sent to the server via an HTTP Request Authorization Header (e.g. Bearer
JWT and cookies can be both used for authentication or authorization, A web cookie may be saved in the Cookies storage of your browser and may contain JWT. There are not many similarities between the two.
Even when there may be similarities, there are also differences between JWT and cookie storage. There are several differences compared to the similarities. They rather have differences instead of similarities, below are a few explained differences between JWT and Cookies storage:
The best alternative option to choose mostly depends on the goals you want to achieve while keeping the targets' convenience, security, and effectiveness in check.
In choosing either JWT or cookies storage, functionality, needs and target should be considered before concluding on what to use.
However, JWT can be stored inside Cookie. This method is safer because attackers won't be able to steal your user's token easily. It's also important to know that cookies are not immune to attacks, more security measures should be implemented for the overall security of the application.
When choosing between JWTs and cookies to store authentication tokens, there are certain security tradeoffs to take into account, proper evaluation should also be considered. It also means that an attacker can access the user's account if a JWT or cookies are intercepted or stolen.
Web Designer and Graphics Designer who writes and codes also.