Showing posts with label Cryptography. Show all posts
Showing posts with label Cryptography. Show all posts

JWT Explained: A Beginner's Guide to JSON Web Tokens

In today's digital world, security plays a vital role in keeping sensitive information secure from unauthorized access. One of the most popular ways to secure data transmission over the network is through the use of JSON Web Tokens (JWTs). In this blog, we will discuss what is JWT, why it is used, and provide some examples.

What is JWT?

JSON Web Tokens (JWTs) are an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. JWTs are digitally signed using a secret (with HMAC algorithm) or a public/private key pair (with RSA or ECDSA algorithm), which can be verified and trusted by servers. JWTs can be used for authentication, authorization, and information exchange.

Why is JWT used?

JWTs are used because they are:

  1. Secure: JWTs use cryptography to sign and verify the content, which makes it challenging for an attacker to tamper with the data.

  2. Stateless: JWTs are self-contained and do not require the server to keep track of a session. This means that JWTs can be used in a distributed environment, such as microservices or serverless applications.

  3. Compact: JWTs are compact and can be easily transmitted over HTTP headers or in URLs.

  4. Interoperable: JWTs are widely used and supported by different platforms and programming languages.

Components of JWT:

A JWT consists of three parts:

  1. Header: The header typically consists of two parts: the type of token, which is JWT, and the signing algorithm being used (e.g., HMAC-SHA256 or RSA).

  2. Payload: The payload contains the data that is being transmitted, which can include user information, authorization data, or any other relevant information. The payload can be encrypted for added security.

  3. Signature: The signature is generated by combining the header and payload with a secret key, using the specified signing algorithm. This ensures that the contents of the token have not been tampered with during transmission.

Example of JWT:

Here is an example of a JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

This JWT consists of three parts:

  1. Header:

{ "alg": "HS256", "typ": "JWT" }

  1. Payload:

{ "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }

  1. Signature:

HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)

In this example, the secret key is used to sign the header and payload, and the resulting signature is appended to the JWT. The server can verify the authenticity of the JWT by verifying the signature using the secret key.

References:

  1. https://jwt.io/introduction/
  2. https://tools.ietf.org/html/rfc7519
  3. https://auth0.com/learn/json-web-tokens/