1, Cookie,

Data stored (usually encrypted) on a user’s Client Side by some web sites to identify the user.

HTTP is a stateless transport protocol that cannot distinguish and manage requests and responses by state. In other words, the server has no way of knowing the identity of the client from the network connection alone. The client then issues a pass – cookie to distinguish, this is how cookies work.

The server tells the client to write the cookie through the set-cookie of response, and subsequent requests will carry the cookie.

Cookies have the following important parameters:

2, the Session

Session is another mechanism for recording the state of the session between the server and client. The session is stored on the server, and the session key (sessionId) is stored in the cookie of the client.

According to the above process, the session transmits the sessionId through cookies to achieve user authentication. In addition, the sessionId can also be passed without cookies. For example, the response is returned to the client and then passed to the server as a parameter of the request for verification.

Cookie and Session comparison
  • Security: The Session is more secure than the Cookie. The Session is stored on the server and the Cookie is stored on the client.
  • The type of storing values: Cookie only supports string data. If you want to set other types of data, you need to convert them to strings. Session can store any data type.
  • Validity period: Cookies can be set to remain for a long time. For example, the default login function that we often use, the Session usually expires for a short time, and the client is closed (by default) or the Session times out will be invalid.
  • Storage size: The data stored by a single Cookie cannot exceed 4K. The data stored by a Session is much higher than that stored by cookies. However, too many visits will occupy too many server resources.
The session faults:
  • Resource usage: Each authenticated user stores a session in the memory. However, as the number of authenticated users increases, the overhead on the server is high.
  • CSRF attack: User identification based on cookies is vulnerable to cross-site request forgery if the cookies are intercepted.

3, Token

A token is a string of characters and is used as an authentication credential. The most commonly used scenario is API authentication.

Generally speaking, there are three main types of tokens:
  • Custom token: A token customized by the developer based on the business logic
  • JWT: JSON Web Token, a Token specification defined in RFC 7519
  • Oauth2.0: An authorization specification defined in RFC 6750, which is not actually a token, but has a token in it.
Token features:
  • Stateless server and good scalability
  • Supports mobile devices
  • High safety
  • Support for cross-program calls
Token authentication process:

Refresh Token

Refresh Token Is a token dedicated to refreshing access tokens. The Access Token has a short validity period. When the Acesss Token expires, you can obtain a new Token by using the Refresh Token. If the Refresh Token expires, you can only log in again.

The difference between Token and Session
  • Session is a mechanism for recording the Session status between the server and the client. The server is stateful and can record Session information. Tokens are tokens, resource credentials needed to access resource interfaces (apis). Token makes the server stateless and does not store session information.
  • Session and Token are not contradictory. As an authentication Token, the security of the Session is better than that of the Session, because each request has a signature and can prevent listening and
  • Replay attack
  • The Session must rely on the link layer to ensure communication security. If you need to implement stateful sessions, you can still add sessions to store some state on the server side.
  • Session authentication is simply storing User information in the Session. Because of the unpredictability of the SessionID, it is considered safe for the time being. Tokens, if referred to as OAuth tokens or similar mechanisms, provide authentication and authorization, authentication for the user and authorization for the App. The goal is to give an App access to a user’s information.

4, JWT

JSON Web Token (JWT) is the most popular cross-domain authentication solution. It is an authentication and authorization mechanism and an open standard based on JSON.

JWT composition
A JWT token is a string consisting of a header, payload, and signature, with a. The format is as follows: base64(header). Base64 (json payload). SignatureCopy the code

For details, see: Ruan Yifeng JSON Web Token Tutorial

JWT certification process:
  1. After a user enters the user name and password to log in, the server returns a JWT to the client after successful authentication.
  2. JWT is stored locally by clients and is added in Bearer mode in the Authorization field of request headers when users wish to access a protected route or resource.
  3. The protected route on the server side will check the JWT information in the request header Authorization and allow access if it is valid. Because JWT contains some user information internally, it reduces the need to query the database.
How JWT is used

When a user wants to access a protected route or resource, it can be automatically sent in a cookie, but this cannot be cross-domain.

2. Stored in localstorage and added to header in the Authorization field of HTTP request header information when sending requests, JWT is added in Bearer mode.

Authorization: Bearer <token>
Copy the code

3. The JWT can be placed in the body of a POST request via the interface parameter, or transmitted via the queryString of the URL.

Customize the relationship between Token and JWT

Similarities: Both are tokens to access resources, both record user information, both make the server stateless, and only after the authentication is successful, the client can access the protected resources on the server

Difference: The server verifies the token information sent by the client and queries the data. JWT does not need to verify the token information sent by the client, but can use the key verification on the server instead of the database query.

5. Various authentication methods should be noted

Pay attention to cookies
  • Because the storage is stored on the client, it is easy to be tampered with by the client. Therefore, you need to verify the validity before using the storage
  • Don’t store sensitive data, such as user passwords and account balances
  • Using httpOnly improves security to some extent
  • Minimize the size of cookies. The amount of data that can be stored cannot exceed 4KB
  • Set the domain and path correctly to reduce data transfer
  • Cookies cannot cross domains. Subdomain names can access parent domain names
  • A browser can store a maximum of 20 cookies for a website, and a browser is generally allowed to store only 300 cookies
  • The mobile terminal does not support cookies very well, and the session is generally implemented based on cookies, so the mobile terminal is commonly used by token
Note the use of sessions
  • If a large number of users are online at the same time, session storage occupies a large amount of memory on the server. Therefore, you need to periodically clear expired sessions
  • When a website is deployed in a cluster, session sharing among multiple Web servers is a problem. Because sessions are created by a single server, the server that handles user requests may not be the same server that created the session, so that server cannot retrieve information such as login credentials that was previously put into the session.
  • When multiple applications want to share a session, cookies need to be processed across domains in each application because different applications may be deployed on different hosts.
  • The sessionId is stored in a cookie. If the browser forbids cookies or does not support cookies, the sessionId will be followed by the URL parameter to rewrite the URL, so the session does not need to rely on cookies to implement
Note to use token
  • If you think using a database to store tokens will take too long to query, you can choose to store them in memory. For example, Redis is suitable for your token query needs.
  • The token is completely managed by the application, so it can bypass the same-origin policy
  • Tokens can avoid CSRF attacks (because cookies are no longer needed)
  • The mobile terminal does not support cookies very well, and the session needs to be implemented based on cookies, so the mobile terminal is commonly used by token
Considerations when using JWT
  • JWT is not encrypted by default, but it can be encrypted. Once the original Token is generated, it can be encrypted again with the key.
  • Secret data cannot be written to the JWT without encryption.
  • JWT can be used not only for authentication, but also for information exchange. Using JWT effectively can reduce the number of times the server queries the database.
  • The biggest advantage of JWT is that servers do not need to store sessions, which facilitates the expansion of server authentication and authentication services. However, this is the biggest drawback of JWT: since the server does not need to store Session state, there is no way to discard a Token or change its permissions during use. That is, once a JWT is issued, it remains valid until expiration, unless the server deploys additional logic.
  • The JWT itself contains authentication information, and if it is disclosed, anyone can gain full access to the token. To reduce theft, JWT expiration dates should be shorter. For some important permissions, the user should be authenticated again.
  • JWT is suitable for one-time command authentication, issuing a JWT with a very short validity period. Even if exposed, there is little risk because new JWT will be generated for each operation, so there is no need to save the JWT and truly achieve stateless.
  • To reduce theft, JWT should use HTTPS instead of HTTP.

References:

  • Ruan Yifeng explains JWT
  • Jsonwebtoken library
  • The difference between session and Token
  • The difference between session and cookie
  • Cookie, Session, Token, JWT
  • JWT,
  • Front – end authentication