prospect:
On Friday, the backend asked me to check from the front-end project whether there were cookies set. I was questioned four times in a row when I said nothing in a row. Finally, I said no, and it ended in disagreement. Based on distrust of the front end, write a small essay to explain how to set cookies in the front end of the vue
The conceptual nature of cookies will not be described here.
1: Cookie generation mechanism
- The server generated, inHttp response headerRespond-HeaderSet-Cookie
- Client generation
Two: Server generation
- Server sideCookie (key=value) can be set through the constructor and instance method of the cookie class and returned.
- BrowserReceived a response and foundResponse headerThere is a Set-Cookie in it, and the browser will save the key and value in the browser.
- In subsequent requests initiated to the same domain name,BrowserWill be hereRequest headerAdd the cookie field to it (unless it expires).
The server side uses Set-CookieExpires andMax-AgeTwo attributes to set the validity period of a cookie
1、Expires
Set-Cookie: sessionId=abc123; Expires=Thu, 01 Jan 1970 00:00:00 UTC;
The value of Expires must be a complete date and time, including year, month, day, hour, minute, second, and time zone.
- Expires value isPast Times, the browser immediately deletes the cookie;
- Expires value isIn the future, the browser will delete the cookie at that point in the future
2、Max-Age
Set-Cookie: sessionId=abc123; Max-Age=0;
The value of Max-Age is a second value.
- Max-Age = 0; the browser deletes the cookie immediately
- Max-Age = -1; The cookie disappears after the browser restarts. Close the current tab or close the browser, and the cookies will disappear.
- Max-Age=3600; means that it is valid within 3600 seconds (i.e. 1H), and expires after the deadline.
When setting these two attributes at the same time,Max-Age Priority is higher than Expires
Three: Client generation method
- JavaScript comes with
- Third-party dependency library: such as js-cookie
1、
// Set cookies = 'sessionId=abc123; path=/' // Get the cookie valueconst getCookie = name => { var cookies = (";"); for (let i = 0; i < ; i++) { const [key, value] = cookies[i].split("=") if (() === name) { return value; } } return "" }; // Delete cookies// Method: Specify the expires attribute of the cookie as a past timeconst deleteCookie = name => { = name + '=;expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'; } deleteCookie('password');
2、js-cookie
import Cookies from 'js-cookie'; // Set cookies('sessionId', 'abc123'); // Get cookiesconst sessionId = ('sessionId'); // Delete cookies('sessionId');
Four: ----------- I am the dividing line --------
Whether the front-end sets cookies, search the cookie keyword globally in the project to determine whether the front-end has done special processing.
Cookies are automatically managed through the browser, and in most cases the front-end does not need to process cookies.
Browser local data storage: It is recommended to use web storage (including localStorage and sessionStorage). Larger storage space (about 5M), multiple attributes and methods are provided, making data operation easier.
V: Authentication
1) Disadvantages of cookies
- Unsafe: The key-value pairs of cookies are all plain text. Users can get cookies through browsers or other tools, which may be tampered with (), which poses a security risk. Due to the security issues with cookies, some companies' intranet or security policies will require cookies to be disabled.
- Capacity limit: The size of each cookie does not exceed 4KB, and there is a limit on the number of cookies set by a single domain name.
- Cannot save instances
- Some devices or browsers may not support cookies
- Cross-domain issues
- ...
Due to the above shortcomings, cookies are not suitable for authentication and need to be cooperated with session.
2)Session
Cookies return the content (key, value, etc.) through the response header. If these contents are not returned directly, but are saved on the server side, give the content a name called the session context, and give the context an id called SessionId (anything is OK). The client and the server are associated with the SessionId.
SessionId is usually stored in the client as a cookie. But cookies are not the only way, URLs are OK. However, the URL method is not user-friendly, so basically no Internet project will adopt this solution.
Session Problems
- The size of data stored in the session should be considered as storage limit
- Critical businesses that rely on Session must ensure that the client has turned on cookies
- In the case of load balancing, the implementation of the Session is usually required to be rewrite since the Session exists in the Web server memory cannot be shared.
- There are reasons for the loss of Session content, usually due to the restart of the web server.
Cookies or sessions are dominated by the backend, and the front-end related actions are completed by standard browsers. js is just a work of user experience, not a work at the logical function level
The most common authentication solution now is: Token.
3)Token
Tokens are generated on the server side. The front-end uses the username/password to request authentication from the server. If the server authentication is successful, the server will return the token to the front-end. The front-end can bring a token to prove its legal status every time it requests.
The full name of Token is JSON Web Token, referred to as jwt.
Detailed description
The front-end uses the username/password to request authentication from the server. After the server authentication is successful, the user ID and other information are packaged. When packaging, use secret (HS256 algorithm, RS256 algorithm, etc.) to encrypt it, and the server will return the token to the front-end.
The front-end can't solve the problem by getting the token, because the server will definitely not pass the secret to the front-end, so that the front-end can solve it.
The front-end can bring a token to prove its legal status every time it requests. The backend gets this token in the request header (usually placed in the request header) for verification. Verification mainly ranges from two levels: whether the signature is valid and whether it expires.
Summarize
This is the article about how to set cookies and authentication issues in Vue front-end. For more related content on setting cookies and authentication in Vue front-end, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!