Node.js Authentication with JWT
What is a JSON WEB TOKEN?
JWT (JSON WEB TOKEN) is a standard that defines a compact and self-contained way for securely trasmitting information between parties as a JSON object.
Why JWT?
There are several reasons why applications use JWT for authentication:
- JWT is a good choice to be passed in HTML and HTTP environments due to its smaller footprint when compared to other types of tokens.
- JWT can be signed using a shared secret and also by using public/private key pairs.
- It is easier to work with JWT as JSON parsers are common in most programming
languages.
- JWT is also suitable for implementing authorization in large-scale web applications.
Structure of a JWT
- Header - Consist of two parts: - Type of token, i.w JWT - Signing algorithm, example SHA512
- Payload - Contains the claims that provide information about a user who has been authenticated along with other information like token expiry time
example
{
"sub": "0987654321",
"name": "Jonh Doe",
"admin": true
}
- Signature - Final part of a token that wraps in the encoded header and payload, along with the algorithm and a secret
example:
HMACSHA512(base64UrlEnconde(header)+"."+base64UrlEncode(payload), secret)
JWT USE CASES
- Authorization - This is the most common scenario for using JWT. Once the User is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.
- Information Exchange - JWT are a good way of securely transmitting information between parties.
DEMO CODE
For this demo it is necessary to install express and jsonwebtoken libraries. You can install with the following code: npm install express jsonwebtoken
After the installation create a file called app.js and add the code bellow. This code contains some comments to help you understand.