To protect the private data and resources of the system, users can access the resources of the system only when their identities are valid. Authentication and authorization are required when users log in to the system. After a user is authenticated, the user information can be kept in the session to avoid the authentication for each operation. Session is a mechanism provided by the system to maintain the login status of the current user, including session-based mode and token-based mode.

HTTP Auth Authentication

Encrypts and decrypts user information in MD5 or Base64 mode

  • To reduce the risk of leakage, HTTPS is generally required.
  • Application scenario: It is usually used on systems that do not require high internal security, such as the router web page management interface

Server session+ client cookie sessionId

Session Authentication Process

  • When a user requests the server for the first time, the server creates a Session based on the information submitted by the user
  • The Session id is returned to the browser when the request is returned
  • After receiving the SessionID information from the server, the browser stores the information in the Cookie, and the Cookie records the domain name of the SessionID
  • When the user accesses the server for the second time, the request will automatically determine whether there is Cookie information under the domain name. If there is Cookie information, the server will automatically send the Cookie information to the server, and the server will obtain the SessionID from the Cookie. If the Session id is not found, the user is not logged in or the login is invalid. If the Session id is found, the user is logged in and you can perform the following operations.

Session authentication has hidden risks

  • Session mode Because session information is maintained on the server, it is easy to maintain on a single server. If multiple servers are deployed, session information needs to be synchronized between servers, which makes horizontal service expansion inconvenient.
  • The number of sessions increases as the number of login users increases, and the amount of storage increases significantly.
  • CSRF attacks may occur when the session+cookie stores the sessionId. The common method is to use cSRF_Token to solve the problem

Token-based authentication

As mentioned above, the essence of sessionId is to maintain the user status information on the server side. The token method is to generate a string of tokens from the user status information and pass them to the front end. Then, each time the request is sent, the token is brought back to the server side. After receiving the request, the server parses the token and verifies the relevant information.

Introduction to JWT mode

The common generation method in the industry is JWT (JSON Web Token)

JWT consists of three parts:

  1. Header: describes the metadata of the JWT, defines the algorithm for generating signatures andTokenThe type of.
  2. Payload: Stores the data that needs to be transmitted
  3. Signature (= Signature): The server passes.Payload,HeaderAnd a key (secret) to useHeaderThe signature algorithm specified in it (HMAC SHA256 by default) is generated.

Token authentication process:

  1. The client requests login using the username and password
  2. The server receives a request to verify the user name and password
  3. After the authentication succeeds, the server issues a token and sends the token to the client
  4. After receiving the token, the client stores it, for example, in a cookie or localStorage
  5. Each time a client requests resources from the server, it must carry a token signed by the server
  6. The server receives the request and verifies the token in the request. If the verification succeeds, it returns the requested data to the client

JWT authentication implementation

1. The back-end login interface generates token if(result! == null){ const token = jwt.sign({ name: result.name, _id: result._id }, 'my_token', { expiresIn: '2h' }); Return ctx.body = {code: '000001', data: token, MSG: 'login succeeded'}} 2. Front-end: cache tokens and configure the corresponding header config.headers.common['Authorization'] = 'Bearer '+ token; 3. Koa will use the default authentication mode of THE KOA-JWT middleware for authentication. The middleware will split authentication success and authentication failure.Copy the code

Refresh_token Resolves token expiration

  • Refresh Token Is a token dedicated to refreshing access tokens. If you do not have refresh token, you can refresh the Access token, but each refresh requires the user to enter the login user name and password, which can be troublesome. With the refresh token, this hassle can be reduced. The client directly uses the Refresh token to update the Access token without additional operations by the user.

Scheme selection

In most cases, a more general toke-based approach is adopted. The calculation time of resolving tokens is used to exchange session storage space, ensuring more flexible scalability of the entire system and reducing the pressure on the server.

OAuth2.0 introduction

OAuth (Open Authorization) is an open standard that allows users to authorize third-party applications to access their information stored on another service provider without having to provide a user name and password to third-party applications or share all the content of their data.

About WeChat login function, you can view WeChat official documentation: developers.weixin.qq.com/doc/

Password mode Password

In this mode, the user directly discloses the user name and password to the client, which indicates that the resource owner and the authorization server trust the client to do no harm. This method applies to the scenario where the client is developed internally.

Authorization code mode authorization_code

Wechat login is used in this mode. The flow of this pattern is as follows

The testing process is as follows:

  • (1) the user when applying for access_token (access address http://localhost:53020/uaa/oauth/authorize? Client_id =c1&response_type=code&scope=all&redirect_uri=http://www.baidu.com), the login page will be redirected first, requiring users to log in. — In wechat, the login page is customized to scan the QR code login page.
  • (2) After you log in as the admin user, the default authorization page is displayed. — wechat has customized the authorization page
  • (3) After you agree, you will be redirected to the Baidu webpage designated by us with the authorization code. — In the actual project, it should be a path pointing to the client side project, and the background gets the code and saves it.
  • (4) After getting the code, you can apply for access_token from UAA project

This mode is the safest of the four. In this mode, the three parties of OAUTH2 authentication can complete the guarantee authentication process without mutual trust. Moreover, in this mode, access_token interacts directly with backend servers, which reduces the risk of token leakage.