The author | week sauce

This article was written on June 11, 2021. First in zhouzhoujiang personal blog, reproduced please indicate the source.

In the last article, I described the basic steps of building Nest blog background system. After setting up basic projects and dividing functional modules, I still need to improve it step by step. The first function to be completed is user login authentication. In daily work, each system has the realization of user login state maintenance of this part of the content, but there are always some places a little vague, this time through their own completion of the front-end implementation, deepen the understanding of this aspect.

First, you need to know the basics. Because HTTP is a stateless protocol, each request is completely independent, the server cannot confirm the identity of the current visitor, server and browser in order to carry out session tracking, it must actively maintain a state.

Understand cookies, sessions, and JWT

Cookie

It is a small piece of text information stored on the local machine by the server. After the first login, the server sends a header field called set-cookie to the browser of the client through a response packet. The client saves the Cookie locally. When the browser requests again, the browser automatically sends the Cookie to the server, and the server identifies the user through the Cookie.

There are some drawbacks to using cookies only to store user login information

  • Insecure. Cookies can be intercepted and tampered with, so they cannot store sensitive data
  • Cookies can only store a small amount of data, generally less than 4KB, and the number of cookies is also limited, unable to store a large amount of information.
  • Cookies can be disabled
  • Cookie portability across domains is not allowed

Session

Session is a server-side mechanism. Session objects store attributes needed for a user’s Session, such as login information, memory stored on the server side, caches such as Memcache, or databases. In addition, each client is assigned a unique SessionId as an id. When the client sends a request to the server, it carries the SessionId so that the server knows who the request comes from. As for how the client saves this identity, there are several ways. The most common is using cookies, as shown in the following figure.Session and Cookie are used to maintain the status of requests to the client. However, because the Session is stored on the server, if the Web server uses load balancing, the Session will be lost when the next operation request is sent to another server, resulting in the failure of state maintenance. One way is to persist Session data, writing it to a database or other persistence layer. The alternative is that if you can keep the server from being relevant (that is, the server is stateless), you won’t have this problem.

JWT – JSON Web Token

Token

Before you get to know JWT, you need to know about tokens, which are strings generated by the server and often used as resource credentials to access resource interfaces (apis). After login authentication, the server obtains an authentication string Token. In the subsequent interaction between the browser and the server, the server sends the Token in the request header to the server. The server then obtains the Token for authentication.

JWT

JWT is a normalized Token. JWT consists of three parts: Header Header, Payload Payload, and Signature Signature. JWT is generated from three parts, with “between the three parts. Number to do the partition.

  • Header

Describes the most basic information about the JWT, such as its type and the algorithm used to sign it

  • Payload

Used to store data that actually needs to be passed. The following fields are official, but not mandatory

  • Iss (Issuer) : indicates the issuer
  • Exp (expiration Time) : expiration time
  • Sub (subject) : indicates the topic
  • Aud (audience) : Audience
  • NBF (Not Before) : indicates the effective time
  • Iat (Issued At) : time of issue
  • Jti (JWT ID) : indicates the ID

  • Signature

Is the signature of the first two parts. To prevent data tampering, you need to specify a key, which is stored on the server and cannot be disclosed to users. Then, using the signature algorithm specified in the Header, follow the formula to generate the signature

Based on the configuration information in the case, the resulting JWT is as follows

The composition and generation mode of JWT have been almost understood, so the usage mode of JWT can be seen in the following figure, which intuitively shows the general implementation mode of using JWT as login state retention.

Pay attention to

JWT is not encrypted by default. Anyone who gets a JWT string can decode it to obtain its content, resulting in information leakage. For example, when I get the Payload generated in the middle of JWT (that is, the part where we store user information), I can directly obtain user information, including ID, name, and other information through base64 decoding. Email, etc.

  • Therefore, sensitive information should not be stored in the JWT without encryption (very important), so it can be encrypted again after the Token is obtained.

  • Protect the signature key and do not disclose it to the public, because the general signature algorithm type is public, so it is very easy to guess which one you use. If you know the signature key, you can forge and tamper with JWT, causing security problems.

JWT has some advantages over Cookie+Session:

  1. Not dependent on cookies, JWT can be used as long as the client can store it, so there are no problems caused by cookies being disabled.
  2. The authentication mechanism of JWT is stateless. Authentication information or Session information of users does not need to be retained on the server. In load balancing, Session loss on another server does not need to be taken into account.
  3. Cross-domain authentication, because it does not rely on cookies, you can use any domain name to provide your API services without worrying about cross-domain resource sharing (CORS).

Code implementation

I have said a lot of basic knowledge, such as Cookie, Session, JWT and other login authentication methods. The following is specific to my blog background system is how to achieve, here is the JWT way.

Configuring a Signature Key

Env, read @nestjs/config. Add a config to the. Env to store the key that generates the JWT token. This key needs to be stored properly.

Login interface

Add a login interface in the controller of the user module. After verifying the user name and password, call a custom method to generate JWT and return it to the front end.

Create JWT

ConfigService is injected and Secret is read. JWT is generated using the jSONWebToken tripartite library. The user ID is stored in the JWT content and the expiration time is set.

After login, the browser gets the JWT string from the server, which is stored in localstorage. Each subsequent interface request will be carried in the request header and generally placed in the authorization field.

AuthMiddleware

Then write a general middleware, user information before the need to deal with the authorization of routing certification, is here to get the front end request carry on JWT, then get Secret do authentication, user information of JWT, verification by the user information to be included in the current request object, in the back of the context. This completes the implementation of JWT login state retention.

other

To get the user ID for later use in your business code, you can use a custom decorator in Nest to keep your code concise.

summary

So far, the basic structure of Nest project has been created, and user login authentication has been realized, followed by specific business logic.

For the complete code, visit zzj-admin-API