Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

WeChat Mini Programs simulates how to realize cookie

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces in detail "WeChat Mini Programs Simulation cookie how to achieve", the content is detailed, the steps are clear, and the details are handled properly. I hope this "WeChat Mini Programs Simulation cookie how to achieve" article can help you solve your doubts.

Development background

The existing system already has a complete interface, and the user status and verification are all based on cookie.

Part of the business has to be on Mini Program. As we all know, WeChat Mini Programs does not support cookie. To launch the business, the best way is based on the existing interface, the change is small, but also the fastest.

Simulated cookie

Through the browser's development tool, the Network bar to view the request, the cookie in the browser will be carried in the Request Headers of each http, using Cookie as the key name.

So, in the official request method wx.request of Wechat, we set header, and adding a Cookie should be able to simulate.

Here comes the question of how to get the cookie returned by the server.

Through the login interface (when logging in, the server will implant cookie as session), check the http and go back to it.

Wx.request ({url:'/ api/login', success: (data) = > {if (data.statusCode = 200) {console.log (data); / / data should have the words Set-Cookie or set-cookie, well, that's the cookie}} planted by the server)

Get the cookie and store it locally, and insert it directly the next time you request the data. Perfect.

Format cookie

Originally thought that cookie only needs one in and one out to be perfectly simulated, but the actual operation found that the cookie server carried on could not be recognized.

The cookie returned by the server will carry many fields for storage, such as path=/

/ / cookielet cookie = 'userKey=1234567890; Path=/; Expires=Thu, 21 Jun 2018 13:15:08 GMT; HttpOnly,userId=111; Path=/; Expires=Thu, 21 Jun 2018 13:15:08 GMT,nickName=; Path=/; Expires=Thu, 21 Jun 2018 13:15:08 GMT,userName=111111; Path=/; Expires=Thu, 21 Jun 2018 13:15:08 GMT,imgUrl=; Path=/; Expires=Thu, 21 Jun 2018 13:15:08 GMT';// simulates the required format style let virtualCookie =' userKey=1234567890; userName=111111; userId=111;'

Mom, yeah ~ how to filter it.

A simple and rough filtering scheme is written.

/ / cookie's local storage location const COOKIE_KEY ='_ cookie_key__';/** * format the user's desired cookie * / const normalizeUserCookie = (cookies =') = > {let _ cookies = []; (cookies.match (/ ([\ w\ -.] *) = ([^\ s =] +); / g) | | []. ForEach ((str) = > {if (str! = = 'Path=/) '& & str.indexOf (' csrfToken=')! = = 0) {_ cookies.push (str);}}); wx.setStorageSync (COOKIE_KEY, _ _ cookies.join (''));}

CsrfToken is next used with Egg.js, and Path=/; will be path=/ in some applications.

NormalizeUserCookie mainly filters data such as xx=xxx; and then excludes meaningless data such as path=/;.

When logging in to the interface, save the cookie and bring it in the next request, so it should be, yes, possible, and can be simulated.

The built-in egg-security plug-in with Egg.jsEgg performs CSRF verification by default on all "unsafe" methods, such as POST,PUT,DELETE.

Egg.js can turn off CSRF in the configuration, but what if you have to use it?

First of all, we need to figure out one thing, where did csrfToken come from.

After many times of verification, we know that when a http request is made, the csrfToken value is not carried at the agreed location, and the request will carry a new csrfToken; in the returned cookie. When the request has already carried a value, it will not be generated as a csrfToken. When the csrfToken in the agreed location is consistent with the csrfToken in the cookie, it passes the verification.

After the above formatting user needs the cookie operation, first put aside the csrfToken to deal with the user status and so on.

At the end of each request, try to take the csrfToken that may exist in the cookie separately. If there is a value, cache it. If there is no value, skip the old value.

Encapsulate an Ajax

This Mini Program is based on wepy, so the optimized wepy.request is used.

Based on the Egg.js version.

It may be a little different from the actual development, so modify it appropriately.

Import wepy from 'wepy';export const HTTP_HOST =' http://127.0.0.1:3000';export const HTTP_HOST_API = `${HTTP_HOST} / api/ wxmp`; / / Local storage location of cookie const COOKIE_KEY ='_ _ cookie_key__';// csrfToken local storage location const CSRF_TOKEN_KEY ='_ _ csrf_token__' / * clear user Cookie * / export const cleanUserCookie = () = > {wx.setStorageSync (COOKIE_KEY,'');} / * format cookie * @ param {String} cookies * / export const normalizeUserCookie = (cookies =') = > {let _ cookies = []; (cookies.match (/ ([\ w\ -.] *) = ([^\ s =] +) / g) | | []. ForEach ((str) = > {if (str! = = 'path=/;' & & str.indexOf (' csrfToken=')! = = 0) {_ cookies.push (str);}}); wx.setStorageSync (COOKIE_KEY, _ cookies);}; / * * formatted token * / const normalizeCsrfToken = () = > {let _ value = wx.getStorageSync (CSRF_TOKEN_KEY) | |'' Let _ _ inputs = _ _ value.match (/ csrfToken= [\ S] * /) | | []; let _ key = _ _ inputs [0]; / csrfToken=1212132323; if (!! _ key) {return';} / dehydrated return _ key.replace (/; $,''). Replace (/ ^ csrfToken=/,'');} / * cookie for saving csrf * does not necessarily update cookie * @ param {String} cookie * / const seveCsrfTokenCookie = (cookie) = > {if (cookie) {wx.setStorageSync (CSRF_TOKEN_KEY, cookie);}} / * request data * @ param {Object} opt * / export const doAjax = (opt) = > {return new Promise ((resolve, reject) = > {let Cookies = wx.getStorageSync (COOKIE_KEY) | | []; let csrf = normalizeCsrfToken (); let url = opt.url; / / finishing Cookie Cookies.push (`csrfToken=$ {csrf}; `) / / set the request header opt.header = Object.assign ({'xmurcsrf: Cookies.join ('')}, opt.header | | {}); opt.success = (data) = > {seveCsrfTokenCookie (data.header ['set-cookie']) / / Unified Operation if (data.statusCode = = 200) {if (url ='/ login') {normalizeUserCookie (data.header ['set-cookie']);} resolve (data.data);} else {reject (' unknown error, please try again') }}; opt.fail = (err) = > {reject (err);}; opt.url = `${HTTP_HOST_API} ${opt.url}`; wepy.request (opt);});} After reading this, the article "WeChat Mini Programs simulates how to achieve cookie" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report