Ensuring security in modern web applications is more important than ever. Authentication is one of the cornerstones of this security. In this article, we will discuss how the JWT based authentication system works.
What is JWT?
JWT (JSON Web Token) is a compact and self-contained token format created to ensure the secure exchange of information between web applications and services.
The popularity of JWT stems from the fact that it is both easy to integrate and provides secure data transfer. These tokens in JSON format can be sent between the client and the server and verified on the server side.
Token
A token is a set of characters, usually randomly generated, that represents information or an action. In authentication mechanisms, tokens are used to verify a user's identity or session. For example, a token could be:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
The structure of JWT consists of three main parts: Header, Payload and Signature.
- Header: Specifies the type of token (usually JWT) and the signing algorithm used.
- Payload: Contains the information (claims) to be carried within the token. This information can often be user information, role information, and other properties.
- Signature: This section is created by combining and encrypting a secret key with a combination of the header and payload. The signature is used to verify that the token arrived unaltered.
Since the header and payload are in JSON format, it gave its name to the token type.
Encryption Process
Encryption is the process of converting information into an unintelligible form in order to prevent the information from being read by unauthorized persons. A wrench is usually used in this process. Encrypted information can only be returned to its original state with a suitable decryption key. For example, “Hello World!” When the text is encrypted, an output like Q3J5cHRlZCBUZXh0IQ== can be obtained.
JWT Example
Base64Url format encoding is used to securely transport the information contained in the JWT in URL and HTTP headers. Header:
{
"alg": "HS256",
"typ": "JWT"
}
When encoded in Base64Url format:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
Payload:
It can hold the data we will use to identify the user and the expiration date.
{
"user_id": 123,
"username": "exampleUser",
"exp": "2023-10-07T16:22:35.994721"
}
When encoded in Base64Url format:
eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoiZXhhbXBsZVVzZXIiLCJleHAiOiIyMDIzLTEwLTA3VDE2OjIyOjM1Ljk5NDcyMSJ9
Signature: Header and payload Base64Url formats are merged with ".":
eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoiZXhhbXBsZVVzZXIiLCJleHAiOiIyMDIzLTEwLTA3VDE2OjIyOjM1Ljk5NDcyMSJ9
We obtain the signature by encrypting this value with a secret key (e.g. “mysecretkey”) using the HS256 algorithm. Signature:
TNnYpMANsCSCI2BELs-3Y9PdZosbvI2orzVgpgnSDqw
Add this to the end with “.” and we get the JWT:
eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoiZXhhbXBsZVVzZXIiLCJleHAiOiIyMDIzLTEwLTA3VDE2OjIyOjM1Ljk5NDcyMSJ9.TNnYpMANsCSCI2BELs-3Y9PdZosbvI2orzVgpgnSDqw
PyJwt
We can perform the above operations using Python and the PyJwt library as follows:
import jwt
from datetime import datetime, timedelta
# Anahtar ve algoritma
SECRET_KEY = "mysecretkey"
ALGORITHM = "HS256"
# Başlık ve yük verileri
header = {
"alg": ALGORITHM,
"typ": "JWT"
}
payload = {
"user_id": 123,
"username": "exampleUser",
# Son kullanma tarihi (örneğin, 1 saat sonra)
"exp": datetime.utcnow() + timedelta(hours=1)
}
# JWT oluşturma
encoded_jwt = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM, headers=header)
Use of JWT in Authentication
JWT-based authentication is a frequently used method in modern web applications. Essentially, after verifying the user's credentials, the server creates a JWT based on that information and sends it to the client. The client receives this token and sends this token to the server with every request, so the server verifies who the client is and what he can do.
Advantages of JWT
- Statelessness: The server does not store the state of the client. Instead, everything is encoded in JWT. This increases scalability because there is no need to share session information between servers.
- Extensibility: While JWT starts with a few basic information, it can be expanded with additional information (claims) when necessary. This provides a customizable structure based on the application's needs.
- Portability: Because JWTs are small and in a URL-safe format, they can be easily transported in HTTP headers, URLs, and POST data.
What if we didn't use JWT?
To better understand the advantages that JWT brings, let's review what can be done without using JWT and what problems this approach can cause:
- Session-Based Authentication: Traditionally, users' credentials are stored as sessions on the server side. This approach requires the server to store in memory or in the database for each session. This can lead to scaling issues, especially in large-scale applications.
- Session Sharing Issues: When multiple servers are used, session information must be synchronized between all servers. This is a complex process and can have negative effects on performance.
Authentication Flow
- User Login: The user logs into the application with credentials such as username and password.
- Authentication: The server verifies the user's credentials. If the information is correct, the server creates a JWT.
- Token Sending: The server sends the generated JWT to the client. The client stores this token in the browser's "local storage", "session storage" or in a cookie.
- Authorized Requests: The client sends this JWT in the HTTP header with every request it makes to the server. The server verifies the token and, if the token is valid, responds to the client's request.
- Token Expiration: JWT has an expiration limit. Once this period expires, the token becomes invalid. The client must obtain a new token.
Security Measures
- Short-Term Tokens: The short-term nature of tokens ensures that the damage is limited even if a token is seized. If the token has expired, the client must authenticate again to receive a new token.
- HTTPS: JWTs can contain sensitive information, so all communication between the application and the server should be done over HTTPS.
- Token Storage: We must be careful when storing JWTs in the browser. Storing it in cookies may make it susceptible to XSS attacks. Storing on local storage runs the risk of CSRF attacks. Both methods have risks, so it is necessary to carefully consider their use.
Popular Uses of JWT
Thanks to the flexibility, scalability and portability offered by JWT technology, it appears in many modern technologies and applications. Here are some technological areas and platforms where JWT is popularly used:
- Single Page Applications (SPA): Modern frontend libraries and frameworks such as React, Vue.js and Angular often prefer JWT-based authentication when connected to serverless architectures or API-based services.
- Mobile Applications: Mobile platforms use JWTs to authenticate the user and communicate securely with API services. JWT is an ideal option, especially for cross-platform applications.
- Microservice Architectures: In microservice architectures, where small, independent services come together to form a large application, JWT is frequently used to ensure secure data exchange between services.
- Cloud Services: Major cloud service providers such as AWS, Google Cloud, and Azure use JWTs for cross-service authentication and authorization.
Conclusion
JWT is a powerful tool widely used for authentication and authorization in modern web applications. It is preferred in many applications and services thanks to its advantages such as flexibility, scalability and portability. However, like every technology, there are some important points to consider when using JWT. It is important to use these aspects correctly to optimize security and performance.
See you in the next articles about topics that need more detailed explanation, such as “access” and “refresh token types used with JWT, and how to invalidate tokens correctly in case of session termination!