Wechat small program in general, is login free, adhering to the dragon’s concept of running out. Unless we need to obtain the user’s information, such as the user’s wechat nickname, avatar, geographic location, etc., we need to obtain some information of the user. Wechat official provides the relevant API.

However, in some special applications, it is far from enough to obtain only the information of the login user. Generally, small programs with slightly complex business logic have their own user system, and users need to be authenticated or authorized when communicating with the front and back ends. The mini program must be authenticated and authorized by the wechat account, and then communicate with a third-party server (i.e. our own server) for users to log in. This involves the coupling of wechat account information and third-party user information.

Log in principle

First of all, let’s summarize the fact that login is to ensure two questions:

  • Save login status

  • Security verification

The saving of login status means that after successful login, the client and server perform user validity verification according to established rules without having to log in again when requesting the data interface.

Security verification is meant to counter traffic hijacking, to prevent man-in-the-middle attacks, to insert crap into our pages. HTTPS can deal with the vast majority of application scenarios, effectively prevent traffic hijacking, so wechat small program front and back end communication wechat official forced everyone to use HTTPS, is also based on this aspect of thinking. But while the priest climbs a post, the devil climbs ten, and the wisdom of the program ape is infinite. The upper echelons of the market are churning out dark tech software, such as Fiddle and Charles. The score for swipehop, which became popular in early 2017, relies on these tools to obtain users’ private information. It’s a tool that acts as a middleman and captures secret data. In other words, we can use these tools to crack small program source code. I can write another article to share with you.

All right, got itA concept. Let’s review how traditional browser-based applications solve this problem. Login status saving in the browser environment is usually usedcookieThe implementation principle of this scheme is issued by the browserhttpThe request ofheaderWill carry the clientcookie. The diagram below:

 

  Custom security authenticationThe usual scenario is that the client and the server agree on an authentication signature, and the client issues the signaturehttpBefore the request according to the agreed algorithm to calculate a signature string, and inhttpThe request passes the parameters for calculating the signature to the server. After receiving the request, the server parses the signature string and the calculation parameters passed by the client, calculates the signature string according to the same algorithm, and compares it with the signature of the client. If the signature is identical, the authentication succeeds; otherwise, the data fails to pass the authentication. The diagram below:

  

So let’s look at an example, just to keep it simple, so we don’t have to add the encryption algorithm and so on. We generate the token directly as the signature of the communication. Here we go:

@GetMapping("/login") public ModelAndView login(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map) { //1. Authentication, access to user login information... Do something //2. Generate the user login status token and store it in the distributed storage system, for example Redis String token = uuID.randomuuid ().toString(); Integer expire = RedisConstant.EXPIRE; redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX, token), openid, expire, TimeUnit.SECONDS); Set (response, cookieconstant. token, token, expire); // set(response, cookieconstant. token, expire);return new ModelAndView("redirect:" + projectUrlConfig.getSell() + "/sell/seller/order/list");

    }Copy the code

Through the previous round, we generated user login authentication information on the server side and saved this information to the cookie on the client side. Then we can use this authentication information to judge on the server side, to cuihua code:

@Before("verify()")    public void doVerify() { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); Cookie cookie = cookieutil. get(request, cookieconstant.token);if (cookie == null) {
            log.warn("[Login verification] No token found in Cookie"); throw new SellerAuthorizeException(); } / / 2. Go to the distributed storage system with a second validation String tokenValue = redisTemplate. OpsForValue () get (the String. Format (RedisConstant TOKEN_PREFIX, cookie.getValue()));if (StringUtils.isEmpty(tokenValue)) {
            log.warn("[Login verification] No token found in Redis");            throw new SellerAuthorizeException();
        }Copy the code

In this way, we can determine whether this is a real request from the current real user by using section-oriented programming or in filter after the user request. This way, we can filter out malicious attacks and some crawlers.

Through the above example, we understand the principle of user login mechanism based on browser application. The preconditions for the establishment of the above process are:

  • The browser can obtain the UA information

  • The HTTP request header sent by the browser carries UA information, which can be obtained by the server

So, can we reuse this mechanism for small program development? Unfortunately, the answer is no. Because applets have the following limitations:

  • Cookies are not supported, so using cookies to store login status is not feasible.

  • The HTTP request header does not carry device information and cannot be obtained by the server.

But while I’m poking fun at the limitations of applets, the good news is that HTTP requests can have custom headers.

With the limitation of not being able to use cookies for login identification information we have two ways of transmission:

  • url query

  • http header

However, the semantics of URL Query (usually called data) should be closely related to the function of the interface, and the HEADERS of HTTP requests are more confidential than THE URL Query data, so I finally use the header to pass authentication information scheme.

Login Implementation Scheme

With the technical solution settled, there are still a lot of details to be worked out to implement your own user login under the applets. Let’s start with the official documentationThird-party Login Flowchart:

The process described in the official document is the basic process for implementing third-party login. However, there are still some details in the specific login functions, such as:

  • Mobile verification code login;

  • 3rD_session and openId cannot be exposed to the client in plaintext and need to be encrypted.

  • The validity period for saving login status;

  • The server on which the user logs in is not the same server as the underlying service.

In the applets login mechanismbasisFinally, the following scheme was developed:

Compared with the official wechat login flow chart, there are the following details:

  • 3rD_session and openId are not directly exposed to the client. Instead, they are encrypted using reversible encryption algorithms and then combined into tokens to be exposed to the client.

  • The signature is not verified when the basic function server is requested for the first time. The purpose of this request is to obtain 3rD_session and openId from the wechat server and encrypt them and return them to the client for subsequent requests.

  • The target of the second request is the user server, which carries the token sign. The user server first performs signature verification and mobile phone verification code verification.

  • After the authentication succeeds, the token is parsed to obtain 3RD_session and openId, and then the token is recalculated with uid. Finally, the UID and token are returned to the client.

  • After a user logs in successfully, the client stores the UID and token locally for future use by the request data interface.

  • Clients can store tokens and UUIds using storage or app.globalData.

conclusion

It takes some effort to implement their own user system in wechat mini programs. Each company has its own user login verification system, and security and state preservation issues also need to be considered. With applets that do not support cookies and HTTP request headers that do not carry device information, the details of implementing the login function require some compromise. Often these schemes are bloated and difficult to maintain, testing the developer’s abstractions.


Willing to share and exchange various technologies, personal public account [Mindev], and Knowledge planet [Geek World].



Welcome to subscribe to the public account, daily more yo ~~~