navigation

[Deep 01] Execution context [Deep 02] Prototype chain [Deep 03] Inheritance [Deep 04] Event loop [Deep 05] Curri Bias function [Deep 06] Function memory [Deep 07] Implicit conversions and operators [Deep 07] Browser caching mechanism (HTTP caching mechanism) [Deep 08] Front-end security [Deep 09] Deep copy [Deep 10] Debounce Throttle [Deep 10] Front-end routing [Deep 12] Front-end modularization [Deep 13] Observer mode Publish subscribe mode Bidirectional data binding [Deep 14] Canvas [Deep 15] webSocket Webpack HTTP and HTTPS CSS- Interview Handwriting Promise

[react] Hooks

[Deployment 01] Nginx [Deployment 02] Docker deployVue project [Deployment 03] gitlab-CI

[source code – Webpack01 – precompiler] AST abstract syntax tree [source code – Webpack02 – Precompiler] Tapable [source code – Webpack03] hand written webpack-compiler simple compilation process [source code] Redux React-redux01 [source] Axios [source] vuex [source -vue01] Data responsive and initialized rendering [source -vue02] Computed responsive – Initialization, access, update process

XSS

  • Cross Site Script (XSS) attacks
  • Cross Site Script was originally abbreviated as CSS, but was rewritten as XSS to distinguish CSS from cascading Style sheets
  • Principle: XSS attack refers to an attack in which the attacker injects malicious client code into the website and tampers the web pages of the client side through malicious scripts. In this way, the user can control the user’s browser when browsing the web page or obtain the user’s private data
  • Malicious script: Mainly javascript code, but sometimes HTML and Flash
  • Attack methods: there are a variety of common features: steal user privacy data
  • Attack types: Can be divided into three types, reflective (non-persistent), storage (persistent), DOM based
  • Hazard:
    • Using false input forms to defraud users of personal information
    • Use the script to get the user’s cookie
    • Show fake pictures and articles

Reflective (non-persistent)XSS attacks

  • Reflective XSS simply “reflects” the data entered by the user to the browser. This type of attack often requires the attacker to trick the user into clicking on a malicious link, or submitting a form, or entering a malicious website by injecting a script into the victim’s site.

Stored (persistent)XSS attacks

  • Stored XSS “stores” user-entered data on the server side, and when the browser requests the data, scripts are sent back from the server and executed. This XSS attack is highly stable.

DOM based XSS attack

  • Dom-based XSS attacks are purely client-side attacks that modify the DOM structure of a page through malicious scripts.

Defend against XSS attacks

  • Set httpOnly to prevent cookies from being obtained through script
    • Such asDocument. The cookie properties.The XMLHttpRequest object.Request API
    • XMLHttpRequest for cookies
      • The Cookie cannot be obtained with xhr.getresponseHeader (‘ set-cookie ‘) // null
      • Get all simple Response headers via xhr.getallResponseHeader (), excluding the set-cookie field
      • Note: Both methods can only get the simple Response heade, not the set-cookie field
      • XMLHttpRequest is described in detail below
  • Filter check:
    • Filter check on input, Textares, form and other special symbols
    • HtmlEncode: In some cases, user data cannot be strictly filtered and labels need to be converted
    • JavaScriptEncode
(1) the HtmlEncode: Used to convert the HTML tag < -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- & lt > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- & gt & -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- & amp ' ' -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- & quot Spaces -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- & NBSP JavascriptEncode (2) : For some special symbols for transcoding js "-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - \" \ n -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \ \ n \ r -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \ \ rCopy the code

CSRF

  • Cross Site Request Forgery (CSRF) Cross-site Request ForgeryForgeries: Meaning counterfeit goods
  • CSRF is an attack that hijacks trusted users to send unexpected requests to the server
  • Principle:
    • Mainly through the access to the user in the target site of cookies, diddle the trust of the target site server, the user logged target to stand under the premise of access to the attacker phishing site, the attacker via the url call directly to the target station interface, forgery attacks user behavior, this behavior usually users are unaware of.
    • With cookies, you can do a lot of things: send emails, send messages in your name, steal accounts, buy goods, transfer virtual money, and so on
Case: CSRF attack ideas: (core 2 and 3) 1, users browse and log in to trusted websites (such as: Taobao) 2, after successful login, the browser generates information storage (such as: cookie) 3, users do not log out of Taobao, access to dangerous websites // Attention: If the cookie is not set to expire or is null, the default is session-cookie. When the browser is closed, the cookie is cleared. 4, there is malicious code in the dangerous website, the code is to send a malicious request (such as: Purchase item/balance transfer) // The request carries the information just generated in the browser (cookie), 5. Taobao verifies that the request is legitimate (it cannot tell whether it is sent by the user or not) // Uses the Refer header in HTTP to prevent // The Refer can check the source of the request, and only the legitimate source of the request will be responded by the server. 6Copy the code

Prevent CSRF attacks

  • Verification code: it is considered as the most concise and effective defense method against CSRF attack
    • CSRF often builds network requests without the user’s knowledge, and captcha forces the user to interact with the application to complete the final request
    • Note: For the sake of users, verification codes cannot be added to all operations on the site, so verification codes should only be used as an auxiliary means to defend against CSRF
  • Referer check
    • The Refer field in HTTP indicates the source address of the request. The Refer field can be used to check whether the request comes from a valid source. The server responds only to valid sources
    • 2021/4/7 Correct => referer checks, not refer, to note the spelling of the word
    • 2021/6/21 Correction => Referer is the referer
  • token
    • The main purpose of CSRF is to obtain cookies, so to defend, you need to add information in the request that the attacker cannot forge, and the information cannot be saved in the cookie
    • A randomly generated token can be added to the HTTP request in the form of a parameter, and an interceptor can be set up on the server side to verify the token. If there is no token in the request or the token content is incorrect, the request may be rejected as a CSRF attack.

review

cookie

  • A cookie is a small piece of text stored by the server in the browser. The size of the cookie is no larger than 4KB and is carried on every request
  • Cookies are used to tell if two requests came from the same browser, and to store state information such as the user’s preferred color, font size, and so on
  • The browser cannot accept cookies or send cookies to the browser
  • Window. The navigator. CookieEnabled returns a Boolean value that indicates whether the browser cookie function
  • Document. cookie Returns the cookie of the current web page
  • No more than 30 cookies should be set for a single domain name and the size should not exceed 4KB
  • Cookie sharing conditions: The domain name and port must be the same, but the protocol must not be the same
  • Cookie generation: Cookies are generated by the HTTP protocol and are mainly used by the HTTP protocol

HTTP response: Cookie generation

  • Cookie generation: The server saves cookies by setting the SET-cookie field in the HTTP response header
  • The HTTP response header can containMultiple set-cookie fields
  • In addition to the value of the cookie, set-cookie can also be attachedCookie properties, can contain more than one property, no order required
HTTP/1.0 200 OK content-type: text/ HTML set-cookie: yummy_cookie=choco set-cookie: tasty_cookie=strawberry set-cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly // Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly multiple attributes, no order required [Page Content]Copy the code

How does the server modify an existing cookie

  • The cookie’s key, domain, path, and secure all match
  • Whenever one property is different, a whole new cookie is generated
Set-Cookie: key1=value1; domain=example.com; path=/blog Set-Cookie: key1=value2; domain=example.com; => cookie: key1=value1; => cookie: key1=value1; => cookie: key1=value1; Key1 =value2 // Note: The two cookies have the same name, but the more accurate cookie is listed firstCopy the code

The only way to delete an existing cookie

  • Set the Expires property to an expiration date

HTTP request: Send a cookie

  • When the browser sends HTTP requests to the server, each request carries a cookie
    • (That is, the browser sends back to the server the cookies previously stored on the browser.)
    • The Cookie field is used when sending
    • The set-cookie field is used for generation
  • The Cookie field can contain multiple cookies, using; Division of no.
GET /sample_page. HTML HTTP/1.1 Host: www.example.org Cookie: yummy_cookie=choco; tasty_cookie=strawberryCopy the code

When a server receives a cookie from a browser, there are two things it doesn’t know

  • Cookie attributes: Expires, max-age, Domain, Path, Secure, HttpOnly
  • Which domain name set the cookie, the first level domain name set, or the second level domain name set

The attribute of the Cookie

Expires, Max – Age

  • Expires: Specifies a specific expiration time in UTC format
    • You can useDate.prototype.toUTCString()Format conversion
    • If the Expires attribute is not set, or null is set, the cookie is session-cookie and is valid only for the duration of the session, i.e. when the browser window is closed and the current session ends, the cookie is deleted
  • Max-age attribute: the number of seconds the cookie exists from now on.24 * 60 * 60 * 3651
  • When both Expires and max-age exist, max-age takes precedence

Domain, the Path

  • Domain: Specifies which Domain names to attach this Cookie to when the browser makes HTTP requests
    • If this property is not specified, it is set to the level 1 domain name of the URL
  • Path: Specifies which Path to attach this cookie to when the browser makes HTTP requests
    • Whenever the browser notices that the Path attribute is the first part of the HTTP request Path, it carries this cookie in the header

Secure, HttpOnly

  • Secure: Specifies that this cookie can only be sent to the server under the encryption protocol HTTPS
  • HttpOnly: Specifies the cookie, which is not available through the script
    • The document. cookie property, the XMLHttpRequest object, the Request API can’t get the cookie
    • Document. Cookies, cookies, speaking, reading and writing
      • Document.cookie read: Read all
      • Document.cookie write: Only one cookie can be written at a time. Write is not overwritten, but added
      • The document. cookie read-write difference is related to the HTTPT communication format:
      • Send: HTTP requests to send cookies. Cookie fields. Multiple cookies can be set at a time, separated by semicolons
      • Generation: THE Http response generates a cookie, set-cookie field, one cookie at a time, but there can be multiple set-cookie fields

XMLHttpRequest

  • const api = new XMLHttpRequest()
  • api.open(method, url, async)
  • api.send(body)
  • api.setRequestHeader()
  • api.getResponseHeader() // Get the simple Response header corresponding to the parameter. The parameter must be within the range of the Simple Response Header
  • api.getAllResponseHeader() // Get all simple Response headers
  • api.onreadystatechange()
  • api.onload()
  • api.onprogress() // Download progress
  • api.upload.onprogress() // Upload progress information
  • api.setRequestHeader(name, value)
  • api.responseType // text, document, json, blob, arrayBuffer
  • api.timeout
  • api.abort() // Terminate the request
  • api.withCredentidals // A Boolean value indicating whether cross-domain requests can carry authentication information, such as cookies
Const API = new XMLHttpRequest() (1) api.open() - initializes the HTTP request parameters (URL, HTTP method, etc.), but does not send the request, Open (Method, URL, async, username, password) Method: method of the HTTP request GET, POST, HEAD URL: address of the request async: False: synchronous. Calls to the send method block until the response is fully accepted. // True or omitted: (2) api.send() - Send an HTTP request with an api.send(body) get request written in the send method: The arguments can be written in the open() method to the POST request: (3) api.setrequestheader () - specifies the header of an HTTP request (request header), Call api.setrequestheader (name, value) name only if readyState is 1: The setRequestHeader() method can be called multiple times. The final value is appended to the append instead of overriding the override. The setRequestHeader() method can only be called if readyState = 1, (4) api.getresponseHeader () - Returns the value of the specified HTTP response header (response header) (5) api.abort() // Abort: Abort meaning - Cancel the current response, close the connection and end any pending network activity - api.abort() resets readyState to 0 - Apply: This method can be called (6) api.onreadyStatechange () - api.onreadyStatechange () but multiple times if readyState = 3 - Note: Onreadystatechange is all lowercase, and readyState is the hump of readyState: 0 UNSENT -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- XHR object structure successfully, the open () method is not called 1 OPEND -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the open () method is called, the send () method is not called, SetRequestHeader () can be called 2 HEADERS_RECEIVED -------- Send () method is called, 3 LOADING ----------------- Response Entity Body is downloading, 4 DONE -------------------- The whole data transmission process is finished, regardless of whether the request is successful or failed (7) api.onLoad () - api.onload() is triggered when the request succeeds, ReadyState = 4 - The request succeeds with two callbacks: Onreadystatechange () -2.api.onLoad () method api.onLoad = function () {// If the request is successful if(api.status == 200){//do successCallback}} Status ===200 is incorrect because the negotiation cache returns a status code of 304 and the request is a successful request. So the following judgment with perfect API. Onload = function () {if ((API) status > = 200 && API. The status < 300) | | API. The status = = = 304) {/ / do }} (8) API.timeout-api. Timeout is used to set the expiration time. When is the request over? When is the request over? When is the request over? Resolution: (9) api.onprogress() Download progress information (10) api.upload.onProgress = function(e) {upload progress information if (e.lastComputable  ) { const present = e.loaded / e.total * 100; }} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 1. Question 1: How to get Response Provide three properties to get response: (API. Response) and (API. ResponseText) and (responseXML) api.responseText -- api.responseType='text', '', when not set, Response - responseType is "" or "text", and the value is ""; The responseType types are: TEXT, document, JSON, blob, arrayBufferCopy the code

API. GetReponseHeader () and API. GetAllResponseHeader ()

  • Api.getresponseheader () gets the simple Response header specified by the parameter
  • Api.getallresponseheader () gets all simple Resopnse headers
  • Note: Neither of these methods can get set-cookies, either in the same domain or across domains
  • Note: For cross-domain requests, the client can only get the Simple Response header and access-control-exposure-headers
    • Simple response header:
      • Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma
    • Access – Control – Expose – Headers:
      • The server allows the headers to be exposed to the client only if it exists in the response headers of cross-domain requests
      • This field is not included in the response to a co-domain request
      • They expose me to things like that
  • GetResponseHeader () must also be an unbounded argument, otherwise it will refuse to get the unsafe header error

api.withCredentials

  • WithCredentials A Boolean value indicating whether authentication information can be carried in cross-domain requests. The default value is False
    • Such as cookies,
  • Note: Cookies are automatically included in the header of a request in the same domain, but not in the header of a cross-domain request because: As specified in the CORS standard, by default, browsers cannot send any authentication information such as "cookies" and "HTTP authentication schemes" when sending cross-domain requests. Unless xhr.withCredentials is true
  • Cross domain request: So cross domain request
    • Client:Api. withCredentials = true Set this parameter to true
    • Server side (response header) :Access-Control-Allow-Credentials:true

case

Get request go() {console.log('1111111111'); const api = new XMLHttpRequest(); API. Open (" GET ", -- -- -- -- -- the initial HTTP request parameters, request, a url, whether asynchronous' https://bing.ioliu.cn/v1/rand?type=json ', true); api.responseType = 'text'; ------ Text response api.timeout = 5000; API. SetRequestHeader (' content-type ', 'application/json'); ----- must come after open(), Onreadystatechange = function() {------ if (api.readyState === 4 && this.status === 200) {---- this refers to the API instance console.log(json.parse (this.responseText)) ------ this.response gets the same data}} // Onreadystatechange ===4, onload ===4, onload ===4, onload ===4, onload ==4 Should judge 2 xx or the request is successful API 304. Onload = function () {if (API) status > = 200 && API. The status < 300 | | API. The status = = = 304) { Console. log(json.parse (api.responseText), 'onLoad is triggered when the request succeeds '); } } api.send(); ---- Send data}Copy the code

Interview streamlining juejin.cn/post/684490… Juejin. Cn/post / 684490… Juejin. Cn/post / 684490… Meituan juejin. Cn/post / 684490… Zhihu zhuanlan.zhihu.com/p/83865185 XMLHttpRequest segmentfault.com/a/119000000… My Jane books www.jianshu.com/p/7292d8b5d…