Have you ever been to an event where you had to present ID to prove that you were the person who bought the ticket? The act of asking for ID is a form of authentication so that you receive authorization to enter.
On the web, this process works in a similar way. In order to request certain services or access specific pages, you need to identify yourself in some way, and this identification needs to be secure and unique.
In this article you will understand what the JWT (acronym for “JSON Web Tokens”) standard is for authentication, which is widely used on the web.
What is a token?
Nowadays we hear the word token a lot in connection with NFTs, metaverse, cryptocurrencies, etc. But outside this universe, a token is a digital signature, a key.
When you open an account at a bank, you need to set up a password and your personal data. This data is converted into a digital signature that will uniquely identify you to that bank, and every time you access your bank and enter your password and personal data, the bank will understand and confirm that you are that logged in user, similar to how we enter the event when we present our identity document.
There are several algorithms and standards that transform your information into a token, that is, a unique authentication key that makes sense for the service or application you are currently trying to access. One such standard is JWT, which is secure in that it allows authentication between two parties via a signed token.
What is JWT?
A JWT is a standard for authentication and information exchange defined by RFC7519. Inside it, it’s possible to securely and compactly store JSON objects. This token is a Base64 code and can be signed using a secret or private/public key pair.
Signed tokens can verify the integrity of the information contained in them, unlike encrypted tokens that hide this information. If a JWT is signed by a public/private key pair, the signature certifies that the party that has the private key is the one who actually signed it.
How was JWT created?
It is part of a family of specifications: the JOSE family.
JOSE stands for JSON Object Signing and Encryption. JWT is part of this family of specifications and represents the token. Below you can see other specifications from this family:
JWT (JSON Web Tokens): represents the token itself
JWS (JSON Web Signature): represents the signature of the token
JWE (JSON Web Encryption): represents the signature for encryption of the token
JWK (JSON Web Keys): represents the keys for the signature
JWA (JSON Web Algorithms): represents the algorithms for signing the token
Now that you know what a JWT is, what it’s for, and when to use it, let’s take a deeper look at how it works and what the components of a JWT are.
Basic components of a JSON Web Token
A JWT has a basic structure consisting of the header, the payload and the signature. These three parts are separated by dots. So it would look something like this: header.payload.signature. Let’s get a better understanding of each of these parts!
Header
The header of the token is where we pass basically two pieces of information: the alg that tells which algorithm is used to create the signature and the typ that indicates what type of token.
{
"alg": "HS256",
"typ": "JWT"
}
Payload
The payload is the component where we can find authentication data like password and email, for example.
{
"email": "name@example.com",
"password": "agEastvIders"
}
Signature
The token signature is made by encoding the header and payload plus a secret key and is generated by the algorithm specified in the header.
HS256SHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret_key)
The result is three dot-separated strings that can easily be used in HTML environments and HTTP protocols.
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.
eyJlbWFpbCI6Im5hbWVAZXhhbXBsZS5jb20iLCJwYXNzd29yZCI6ImFnRWFzdHZJZGVycyJ9.
stLcZmJGIeGXw_HY9c8A28E9n-B-GLsXYZABCuNA0XA
Creating a JWT token
To get started, let’s create a folder called jwt in the directory you want. Create a javascript file with the name of your choice, I'm using index.js.
Then, install the jwt lib of your choice. There are several libs that help you generate JWTs. I’ll use jsonwebtoken which is one of the most popular, but you can feel free to explore other options.
The first step is import the lib in our file:
const jwt = require('jsonwebtoken');
Now we create our secret key. The idea is that only you know your secret key and that it is difficult for malicious attacks. But it can be literally any string of your choice. This is how mine looks like:
const secretKey = 'Oa1tz8arFmnXURkg4aJQ';
Now let’s create our token using the sign method. This method accepts as parameters the payload, the secret key and the header, in that order.
const myToken = jwt.sign(
{
email: "name@example.com",
password: "agEastvIders",
},
secretKey,
{
expiresIn: "1y",
subject: "1",
}
);
For this JWT, I’m entering an email and password in the payload; my secret key; and in the header I am entering a subject, which in the library in this example works like an id. In addition I’m saying that our token expires in 1 year. By default the encryption algorithm is HS256.
Now if we log this token to the terminal, we should see the following:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im5hbWVAZXhhbXBsZS5jb20iLCJwYXNzd29yZCI6ImFnRWFzdHZJZGVycyIsImlhdCI6MTY2MTU0ODMwNCwiZXhwIjoxNjkzMTA1OTA0LCJzdWIiOiIxIn0.bYWpwadW8xgstrSydwpnGnQExYuFxLMBh3JQRvtEPmw
Verifying our JWT token
To verify our token we can use a method in the jsonwebtoken library itself called decode passing the generated token.
const generatedToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im5hbWVAZXhhbXBsZS5jb20iLCJwYXNzd29yZCI6ImFnRWFzdHZJZGVycyIsImlhdCI6MTY2MTU0ODMwNCwiZXhwIjoxNjkzMTA1OTA0LCJzdWIiOiIxIn0.bYWpwadW8xgstrSydwpnGnQExYuFxLMBh3JQRvtEPmw';
console.log(jwt.decode(generatedToken))
The output of the code is:
{
email:"name@example.com",
password:"agEastvIders",
iat:1661548304,
exp:1693105904,
sub:"1"
}
Where the parameters iat, exp and sub are respectively the creation and expiration dates, in UTC format, when the token was created and when it will expire, and the subject that we passed in our code with a value of 1.
Now, you might be asking yourself, “Now that I know what a JSON Web Token is and how it works, how do I use it in my front-end applications?”
Authenticating with tokens
Imagine you are a developer and you are creating the front-end of an application for a bank. On the login page you take the users’ data and send it to an API using fetch, for example.
fetch(`${baseUrl}/auth/login`, {
method: "POST",
headers: {
"Content Type": "application/json",
},
body: user,
})
.then((res) => {
...
})
.catch((err) => {
...
});
The server will take this data and will return a token that will identify that user. Now, every time this user logs into the platform, he will go through authentication and, if everything is right with the data, he will be authorized to access certain areas of the application, such as viewing the balance. Usually this encryption and token generation is done by the back-end, but you will need to ensure that this logged-in user can continue to access other areas of the application.
You can also save the token in session storage or *local storage *in your browser to ensure that as long as the token does not expire, the user remains logged into the application. In addition, it is important that when logging in, the user is redirected to a home page where he can see other features of the application.
When this user tries to access the page that shows his balance, for example, you can make a request, using fetch passing in the headers an “Authorization” field with the generated token. This will cause the server to check whether or not the user is allowed to access that specific page.
fetch(${baseUrl}/balance
, {
headers: {
"Authorization": Token,
}
})
.then((res) => {
...
})
.catch((err) => {
...
});
Conclusion
In this article, you saw what JSON Web Tokens are, what they are used for, what their components are, and how to use them in your applications. You also saw how to use tokens in a front-end application for user authentication.
Thanks for reading! Follow me and please interact if you liked the content. Have a great day, see you soon! 👋
Top comments (0)