07 - JWT token generation

In this post we shall learn how to generate a JWT token ,which is widely used in all applications as key to exchange data between frontend and backend applications. JWT token is basically a JSON Web token an internet standard for creating data with signature and details ,which can contain details of user of the application.

How is a JWT generated

  • A JWT is generated when a user keys in credentials of application like username and password. The backend service will authenticate the user and generate a JWT token. A token is signed by private key and any service with valid public key can decrypt the data.

Use case of JWT token

  1. The backend services[APIs] can be triggered by any service using a payload[ details required for execution]. However it should be an authorized request and cannot be triggered by any request. JWT token helps here in making sure it is an authenticated request

  2. The APIs need to know which user has requested to give user specific data in response. Like if there is an API to give list of last 5 orders in an application, the API needs to know for which user it needs to pull the data. The JWT token helps here in storing the user_id in an encrypted format. The API will be able to decrypt the data , query the DB and return appropriate response. Sometimes a specific role can also be added in JWT to make sure a role specific response will be provided to front end.

  3. Making sure the user can make calls for limited duration like 60 minutes[ as defined in application]. This is a security measure which ensures in case of any incident the access to application is limited

Code to generate JWT token

Lets have a look at the code to generate JWT token. Refer to file API-Gateway/app/commonlib/auth_external_token_handler.py which has below method

def sign_jwt(user_id: str, customer_data: dict) -> Dict[str, str]:
    try:
        payload = {
        "user_id": user_id,
        "expires": time.time() + 86400,  # 24hrs
        "firstname": customer_data['firstname'],
        "lastname": customer_data['lastname']}

        token = jwt.encode(payload, config.JWT_SECRET, algorithm=config.JWT_ALGORITHM)

        return {
        "access_token": token.decode('utf-8'),
        "user_id": user_id
        }

    except IndexError:
        raise HTTPException(status_code=status.HTTP_424_FAILED_DEPENDENCY, detail="Unable to generate a token")

We are creating a payload with user_id, the time till when the token is valid,firstname and last name of user. Then we are calling an encode method with secret[ which is important to keep safe] and the algorithm used to encrypt the payload.

  • JWT_SECRET - is like a password to encrypt and decrypt payload.
  • JWT_ALGORITHM - is the algo used to encrypt the data. In our case we are using HS256

We are returning the json to the authentication program which will return to the API-Gateway service.

Testing the JWT token generation

To test the JWT token generation , we shall run the API-Gateway,API-Backend and provide the credentials as shown below

image.png

The response of the call is as shown below

image.png

As we see following is the JSON token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHBpcmVzIjoxNjU2MjIzNDc5Ljg3MzE5NSwiZmlyc3RuYW1lIjoiU3Jpa2FudGgiLCJsYXN0bmFtZSI6IlZlbmthdGEifQ.Y9NZ5PEGrw-qz3cVKq2A07LL7SfEK5AxMYk8_OjwUcc

In the next post we shall see how to make sure the calls can be made by authenticated resource.