Cookie session token summary

Development history

  • Background The
    HTTP protocol is a stateless protocol. This request has nothing to do with the previous request, they don't know each other, and they are not related.

    In order to enable all web pages under a certain domain name to share certain data, sessions and cookies appeared.

One, cookie

1. Introduction to cookies

A cookie is a small piece of information stored on the client side, which is used to record the user's status.

  1. The client requests the server,
  2. The server responds and needs to record the user status, and then uses response to send a response to the client. This response header contains the Set-Cookie header. as follows
  3. The browser saves the cookie, and when the second request is made, the browser will automatically add the cookie to the request header
  4. The server checks the cookie to identify the status of the user

Response header:

	Set-Cookie: value[; expires=date][; domain=domain][; path=path][; secure]

2.Cookie characteristics

2.1 Managed by the browser

If the browser does not support cookies (such as the browsers in most mobile phones) or cookies are disabled, the cookie function will become invalid.

Different browsers save cookies in different ways.

The IE browser will save it as a text file under the folder "C:\Documents and Settings\your user name\Cookies". A text file saves a cookie.

2.2 Do not cross domain names

According to the Cookie specification, the browser can ensure that Google will only operate Google’s cookies and will not operate Baidu’s cookies, thereby ensuring the privacy of users.

2.3 Chinese needs to be coded

Chinese is a Unicode character, and English is an ASCII character
. Chinese can only be encoded in a cookie. Generally use UTF-8 encoding. Chinese encoding such as GBK is not recommended, because browsers may not support it, and JavaScript does not support GBK encoding

2.4 can save binary images

Need to use BASE64 encoding

Not practical. Since the browser will carry cookies every time it requests the server, the content of cookies should not be too much, otherwise the speed will be affected. The content of the cookie should be small and refined.

2.5 read cookie

When the browser submits a cookie, only the name and value attributes will be submitted. Other attributes such as maxAge attribute are only used by the browser to determine whether the cookie has expired

3. Cookies commonly used attributes

Java encapsulates Cookie into javax.servlet.http.Cookie class. Each Cookie is an object of the Cookie class. The server operates the client Cookie by operating the Cookie class object.

Get all cookies submitted by the client through request.getCookie() (returned in the form of an array of Cookie[]), and set cookies to the client through response.addCookie(Cookiecookie)
Insert picture description here

3.1 maxAge validity period

-1 (default value):

  • Temporary cookies, will not be persisted, will not be written to the cookie file
  • Only valid in this browser window and the child window opened in this window, the cookie will become invalid after closing the window

0: Delete the Cookie
Cookie mechanism does not provide a method to delete the Cookie, so the effect of deleting the Cookie can be achieved by setting the Cookie to become invalid immediately

positive number:

  • Cookie will automatically expire after maxAge seconds
  • The browser will be persistent, that is, written to the corresponding Cookie file
3.2 secure security attributes

The secure attribute does not encrypt the content of the cookie, so absolute security cannot be guaranteed. If you need high security, you need to encrypt and decrypt the cookie content in the program to prevent leakage.

二、session

1.session introduction

Session is a mechanism used by the server to record the state of the client

2.session life cycle

2.1 It is automatically created when the user accesses the server for the first time. Generally, the Session is stored in the memory.
2.2 As long as the user continues to access, the server will update the last access time of the Session and maintain the Session
2.3 The server will not be active for a long time Session is deleted from memory

3. Common attributes

The class corresponding to Session is javax.servlet.http.HttpSession class

3.1 maxInactiveInterval timeout
  • setMaxInactiveInterval(int seconds) modify the timeout time
  • The default timeout of Session in Tomcat is 20 minutes
修改web.xml改变Session的默认超时时间。例如修改为60分钟:

<session-config>

   <session-timeout>60</session-timeout>      <!-- 单位:分钟 -->

</session-config>

4. Need browser client support

4.1 Store JSESSIONID in cookie

The HTTP protocol is stateless, and the Session cannot determine whether it is the same client based on the HTTP connection. Therefore, the server sends a Cookie named JSESSIONID to the client browser, whose value is the id of the Session (that is, HttpSession.getId() The return value). Session recognizes whether it is the same user based on the cookie.

4.2 The default maxAge attribute is generally –1

The cookie is automatically generated by the server, and its maxAge attribute is generally -1, which means that it is only valid in the current browser and is not shared between browser windows. It will be invalid when the browser is closed.

5. When the browser does not support, URL address rewriting

URL address rewriting is a solution for clients that do not support cookies. The principle of URL address rewriting is to rewrite the id information of the user Session into the URL address.

5.1 Implementation

The HttpServletResponse class provides encodeURL(Stringurl) to implement URL address rewriting. This method will automatically determine whether the client supports Cookie. If the client supports cookies, the URL will be output intact. If the client does not support cookies, the user's Session id will be rewritten into the URL, such as:

response.encodeURL("index.jsp?c=1&wd=Java") 

如果是重定向的
 response.sendRedirect(response.encodeRedirectURL(“administrator.jsp”));

After renewing

<ahref="index.jsp;jsessionid=0CCD096E7F8D97B0BE608AFDC3E1931E?c=
    1&wd=Java">

For WAP programs,

5.2 Attention
  • WAP program
    Since most mobile browsers do not support cookies, WAP programs will use URL address rewriting to track user sessions.

  • tomcat

TOMCAT judges whether the client browser supports Cookies is based on whether the request contains Cookies. Although the client may support cookies, since the first request does not carry any cookies (because there is no cookie to carry), the rewritten URL address still contains jsessionid. When the second visit is made, the server has already written the cookie in the browser, so the rewritten URL address will not contain jsessionid.

5.3 Cookies are prohibited in the session

Since most of the client browsers on WAP do not support cookies, it is better to simply prohibit the Session from using cookies, and it would be better to use URL address rewriting uniformly. The Java Web specification supports disabling cookies through configuration

Method 1: Modify the configuration in the web project

The META-INF folder (same level as the WEB-INF folder, create it if it doesn't exist)
open context.xml (create it if it doesn't exist), and edit the content as follows:

<?xml version='1.0' encoding='UTF-8'?>

<Context path="/sessionWeb"cookies="false">

</Context>
Method 2: Modify the configuration in tomcat

conf/context.xml

<!-- The contents of this file will be loaded for eachweb application -->

<Context cookies="false">

    <!-- ... 中间代码略 -->

</Context>

Note: This configuration only prohibits Session from using Cookie as an identification mark, and cannot prevent other cookies from reading and writing. In other words, the server will not automatically maintain the cookie named JSESSIONID, but other cookies can still be read and written in the program.

Three, token

3.1 Introduction to token

token is also called token, which is composed of uid+time+sign[+fixed parameter]

  • uid: the unique identity of the user
  • time: the timestamp of the current time
  • sign: Signature, compressed into a fixed-length hexadecimal string using hash/encrypt to prevent malicious splicing by a third party
  • Fixed parameters (optional): Some commonly used fixed parameters are added to the token to avoid repeated database searches

Four, cookie session token problems and solutions

4.1 cookie

  • The data saved by the browser for a single cookie cannot exceed 4K. Many browsers limit a site to save a maximum of 20 cookies.
  • Some clients do not support cookies and need to be set manually, such as applets
  • Browsers have restrictions on cookies, and cookies cannot be manually set. There are problems with mixed and nested development, such as small programs that jump to H5 pages and cannot carry cookies.
  • CSRF (Cross Site Request Forgery) attack, this is also easy to solve, many frameworks block this problem

4.2 session

  • Too many sessions are stored in the server, causing pressure on the server
  • Can't fully achieve the load balancing effect

In the case of load balancing with multiple servers, it is difficult to confirm whether the current user is logged in, because multiple servers do not share seesion. This problem can also be solved by storing the session in a server, but the effect of load balancing cannot be fully achieved.

4.3 token

It can be placed in the header and url, and carried in every network access, usually in the header of the request header.

Compared with cookie, token has the function of cookie, and there is no restriction of cookie. For example, other clients will not restrict header cookies. Token is a good substitute for cookies.

to sum up

1. Cookie: Stored on the client side, which is not very safe;
2. Session: Stored on the server side, and generate a Session id to save on the client side. Too many visits will occupy the server's memory and performance;
3. Token: After the first login, the server generates a Token value, saves it in the database, and then returns the Token value to the client and stores it in a cookie. Increase the storage and query pressure of the database;
4. JWT (Json Web Token): used in front-end and back-end separation projects. The server generates it according to the algorithm, and saves the returned result in the client's localStorage or sessionStorage. The client puts the JWT into the Authorization bit in the HTTP Header every time it requests (solving XSS and XSRF problems). Consume the computing pressure of the server.

Reference link

  • https://blog.csdn.net/fangaoxin/article/details/6952954
  • https://www.cnblogs.com/linyuhong/p/9968056.html

Guess you like

Origin blog.csdn.net/dabaoting/article/details/114130793