Location>code7788 >text

How to choose: Session or JWT?

Popularity:945 ℃/2024-12-17 03:05:45

How does the server side verify that the client is logged in?

After a user successfully logs in, the server side issues a credential. After that, each request from the client needs to carry that credential, and the server side verifies the validity of the credential to determine whether the user is logged in and to process the request.

followingSession respond in singingJWT Differences in this regard:

1. What are the contents of the vouchers?

  • Session: A voucher is a simpleID string, which is used to map session information stored on the server side.
JSESSIONID=8C3C44A3A0B522F1B93D3F8C4F17F2E7; Path=/your-web-app; HttpOnly
  • JWT: A voucher is aself-contained tokens, which can be decoded to obtain session information (e.g., user information, permissions, etc.) directly.
//JWT token format
<Header>.<Payload>.<Signature>

//JWT Case Token
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.S5rf1jOSGbHkGBv1buVpzCHYtoJXnJkK9J9M2yExhms

//JWT case token Decode each part
{"alg":"HS256","typ":"JWT"}.{"userId":"1234567890","name":"John Doe","iat":1516239022}.S5rf1jOSGbHkGBv1buVpzCHYtoJXnJkK9J9M2yExhms

//Note: JWT is not encrypting the data, but only providing a signature to prevent the content from being tampered with. both Header and Payload are in plaintext.

2. How are the vouchers transmitted?

  • Session: The server side is passed theSet-Cookie method sends the credentials to the client, which stores them in a cookie and passes them to the client in each request via theCookie The header sends it back to the server.
  • JWT: The server returns the credentials to the client, which stores them in thelocalStorage maybesessionStorage in. In subsequent requests, the client passes theAuthorization header passes the JWT to the server.

3. How are credentials detected on the server side?

  • Session: The server side is based on the receivedsessionId Query the session information, if the session exists, the authentication passes and the server continues to process the request.
  • JWT: The server verifies the signature in the JWT, the signature passes indicating that the credentials have not been tampered with and were indeed issued by the server. (Remember to change the JWT signing key for the second application, otherwise the JWT of other systems can also access your system)

4. Where is the certification information stored?

  • Session: Authentication information is stored in server-side memory or in a shared memory system such as Redis.
  • JWT: Authentication information is stored in the client's credentials, and the JWT token itself contains all authentication information.

About Horizontal Expansion

Disadvantages of Session

When the system has only a single service, session information can be stored inside the application. However, once the service is split into multiple nodes, the session information needs to be migrated to shared storage (e.g., Redis), at which point all service requests must access Redis. At this point, all service requests must access Redis, and if Redis fails or goes down, the service will not work properly until Redis is restored.

Advantages of JWT

One of the main advantages of JWT is itsself-contained feature, all authentication information is stored in the client's credentials. Since JWT's signature is verified by the server's key, the server does not need to access a shared storage system (e.g., Redis), and each service node can verify the credentials independently. This gives JWT an advantage in distributed architectures and avoids the single point of risk in the event of a Redis failure.


About session control

Benefits of Session

Since session information is stored on the server side, the server side can easily manage sessions. For example, if it is necessary tokickerIf the session information is in Redis or in memory, the client's request will be rejected and the user will have to log in again.

Disadvantages of JWT

Since JWT is stored on the client side, the server side cannot delete the client's credentials directly. If you need to realize the kick operation, the server side must record the token ID issued by the user and pass theblacklists to prevent clients from using expired credentials.

There is sometimes a concern that using a blacklist will be similar to the way Session is done, still relying on a central data store. However, this can be addressed in the following way:

  • The central data (Redis) stores user issuance and pushes the blacklist to each application.
  • Each application keeps a copy of the blacklist locally so that it does not need to query the central storage frequently.

In addition, JWT has expiration time, blacklist can set the same expiration time to avoid too much data storage. Moreover, kicking operations are not frequent, so the blacklist will not have a large amount of data.

If you don't need to block the JWT "immediately", consider using theShort life cycle JWT combiningRefresh mechanism. This approach is also very common. That is, the server returns two tokens:

  • access_token (JWT)
  • refresh_token (usually a UUID, the server stores the key in Redis, and the value is the user's information)

Client Usagerefresh_token Generate a newaccess_token

{
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.S5rf1jOSGbHkGBv1buVpzCHYtoJXnJkK9J9M2yExhms
"
    "refresh_token": "c0cdf579-54d5-46fc-8e1b-bd42bd01b556"
}

 


About session storage

  • Session: Since session information is stored on the server side, the server side can store some frequently accessed data in the session.
  • JWT: The contents of the JWT session arestate in writing (laws, rules etc) Although signatures can prevent tampering, they can still be read, so sensitive data should not be placed in JWT. In addition, JWTs are carried with every request, and too much data will consume bandwidth, so it is not suitable to store too much information.

About Page Routing Control

  • JWT well suitedSPA(single-page applications), since page routing control is usually handled by the front-end, and the back-end only verifies data access through JWT.

  • with regards toMPA(multi-page applications), using JWT to control page access can be difficult. This is because in browser behavior (such as page refreshes), JWT needs to be controlled by theAuthorization The header fields are passed, but when refreshing the page, the browser behavior does not directly carry the message.

Solution: The back-end can be used when the user logs in not only on thebody The JWT is returned in theSet-Cookie This way, the client will automatically carry the JWT when requesting, and the backend can validate the token from theCookie maybeAuthorization The two data sources in the header get the token.


summarize

  • Session: Stores session information on the server side, with the credentials being the session ID, suitable for single application scenarios or environments that require shared memory (e.g., Redis), but relies on a shared storage system.
  • JWT: Credentials contain all authentication information and are signed to ensure their integrity for distributed architectures and do not rely on external storage systems.

In a distributed system split into multiple services, JWT avoids the risk of a single point of failure through a self-certification mechanism, while Session requires a reliable storage system to share session information. The specific choice should be based on the size, requirements and fault tolerance of the system.