Session and login mechanism


githubAddress: stamp here



  1. A solution for maintaining state between client and server
  2. The storage structure of this solution


  • BecauseSessionIt is stored in the form of a text file on the server side, so it is not afraid of the client modifying the session content. (you can also use other storage methods such asredis
  • SessionObjects have a lifecycle
  • SessionInstance is lightweight, which means that its creation and deletion do not consume too much resources
  • SessionObject has a cache inside it


SessionObject to store the properties and configuration information required by a specific user sessionwebInformation will not be lost when pages jump

Generally used for the following operations

  1. Stores information that maintains the user’s state throughout the session, such as login information or other information generated when the user browses
  2. Storage only needs to bePage reloadIn the process, orA set of function pagesObjects that remain in state between
  3. Keep the user’sstatus informationFor access at any time from a page on any device.


  1. The more users log in,sessionThe more memory you need
  2. eachSessionThe duration of an object is the time the user accesses plus the time it is inactive.

Why needsession

The HTTP protocol itself is stateless

For example, coffee drinking:

1. The staff in this shop are very good. They can remember the consumption quantity of each customer. As soon as the customer enters the coffee shop, the staff will know how to deal with it. This approach is to support the protocol itself.

2. Send a card to the customer, which records the quantity of consumption, generally with a valid period. Each time a customer presents this card, the consumption will be related to the previous or future consumption. This is done by keeping the state on the client.

3. Send a membership card to the customer, and there is no record of any information except the card number. If the customer shows the card every time he / she consumes, the clerk will find the record corresponding to the card number in the store record book and add some consumption information. This is done by keeping the state on the server side.

Specific mechanism

  1. When a program needs to create asessionFirst, the server checks whether the client’s request contains aSession ID– calledsession id, if it already contains asession idIt means that session has been created for this client before, and the server follows thesession idTake this.sessionRetrieved for use (if not, a new one may be created), if the client request does not containsession id, create asessionAnd generate asessionAssociatedsession idsession idThe value of should be aA string that is neither repetitive nor easy to find rules to imitateThissession idIt will be returned to the client for saving in this response.
  2. BecausecookieIt can be prohibited artificially, and there must be other mechanisms tocookieCan still putsession idPass it back to the server. A technique that is often used is calledURLRewrite

    Two forms:

    //Attach path as URL
    //As query string
  3. Older technology,Hidden Form Field , which is useful in preventing CSRF


Mapping user and data based on cookie

Put the password incookieOnce the password is loved by Chu angai, the mapping relationship will be lost. usuallysessionThe validity period of is usually short, and the data will be deleted after expiration

Once the server detects a user requestcookieNot carried insession_id, which generates a value that is unique and not repeated, and sets the timeout. Regenerate if expired, update timeout if not expired

var sessions = {};
var key = 'session_id';
var EXPIRES = 20*60*1000;
var generate  = function () {
    var session = {}; = (new Date().getTime()) + Math.random();
    session.cookie = {
        expire: (new Date()).getTime() + EXPIRES
    sessions[] = session

function (req, res) {
    var id = req.cookies[key];
    if (!id) {
        req.session = generate();
    } else {
        var session = sessions[id];
        if (session) {
            if (session.cookie.expire > new Date().getTime()) {
                session.cookie.expire = new Date().getTime() + EXPIRES;
                req.session = session;
            } else {
                delete sessions[id];
                req.session = generate();
        } else {
            req.session = generate();

A space saving approach

Because closing the browser will not result insessionRemoved, forcing server toseesionSet an expiration time, when the distance to the client is last usedsessionWhen the time exceeds the expiration time, the server can assume that the client has stopped its activity, and then thesessionDelete to save storage



Data stored in the user’s local terminal

httpRequest auto send except cross domain


Client records user information


Stored on the hard diskcookieIt can be shared between different browser processes, such as twoIEWindow. And for those stored in memorycookie, different browsers have different processing methods.


  1. namecookieName
  2. valuecookievalue
  3. domain: accessiblecookieA domain name can access the cookies of a higher level domain name
  4. expires/Max-Age: expiration time
  5. SizecookieSize
  6. httphttponlyAttribute fortrueIt can not be used.document.cookieGet
  7. secureFortrueOnly inhttpsGet
  8. path: child path access parent pathcookie

Create cookie

document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";

Read cookie


Modify cookie

document.cookie =

In the form of coverage

delete cookie

Set the expiration time to the past time


  1. Storage size

    • cookieThe data size cannot exceed 4K.
    • sessionStorageandlocalStorageAlthough there is also a storage size limitation, thecookieMuch larger, up to 5M or more.
  2. Effective time

    • localStorageStore persistent data. The data will not be lost after the browser is closed unless the data is deleted actively;
    • sessionStorageData is automatically deleted when the current browser window is closed.
    • cookieSet upcookieValid until expiration time, even if window or browser is closed
  3. sessionStorage

    • Session level storage
    • Temporary, page open, page close
    • Data not shared
    • If you want to jump out of a page through the a tag, thensessionStorageShare
  4. localStorage

    • Persistent local storage
    • Permanent storage
    • No cross domain
    • data sharing
  5. cookie

    • cookieIn homology and in accordance withpathSharing between rule documents
    • max-ageSet in secondscookieThe survival period of.
    • Ifmax-ageIf it is 0, it means that thecookie
    • Ifmax-ageIf it is negative, it means thatcookieIt is only valid in this browser window and the sub windows opened in this window. After closing the window, the cookie will be invalid.

How to getcookie

There are two HTTP headers dedicated to setting and sendingcookieYes, they areSet-Cookieas well asCookie。 When the server returns an HTTP response information to the client, if theSet-CookieThis header means to instruct the client to create acookie, and automatically send this in subsequent HTTP requestscookieTo the server, until thiscookieBe overdue. IfcookieIf the lifetime of is the whole session, then the browser willcookieSaved in memory, this will be cleared automatically when the browser is closedcookie。 Another situation is to save it in the client’s hard disk. If the browser is closed, thecookieIt will not be cleared. The next time you open a browser to visit the corresponding website, thiscookieIt will be automatically sent to the server again.

cookieServer side write

//Java writing
response.setHeader("SET-COOKIE", key + "="+ value + ";Path=/;domain="+ domain + ";date="+date);

//How to write in PHP


CSRF (Cross Station Request Forgery)


  1. User C opens the browser and logs in to website a
  2. After successful login, record the login informationcookie
  3. On websiteaOpen web site without exitingb
  4. websitebReturn the attack code after receiving the user’s request to obtain the websiteaOfcookie, and send a request to a website (Note: here are two steps)
  5. websiteaMistakenly thought it was a request from user C

Stealing cookie

Inject a paragraph into the attacker’s server pagejavascriptCode (cross site scripting attack with XSS)



  1. Verificationhttp refererfield
  2. Add token to request address

System developers canHTTPAdd a randomly generated parameter to the requesttoken, and establish an interceptor on the server side to verify thistoken, if not in the requesttokenperhapstokenIf the content is incorrect, it may beCSRFAttack and reject the request.

  1. stayHTTPCustom properties in the header and verify (not compromised)


XSS (cross site scripting attack)


  1. Reflective (non persistent)

Cross site scripting vulnerabilities that can only be triggered by browsers submitting malicious data in parameters every time.

Can turn a domain name to maliciousURL, send that domain name to the user

  1. Storage (persistent)

By submitting malicious data to storage (such as database, text file, etc.),WebWhen the application program outputs, it is a kind of cross site script vulnerability that reads malicious data from the memory and outputs it to the page.

Common attack methods

  1. bypassxss-filter
  2. utilizeimg
  3. Space, enter,tabTo bypass filtering
  4. Use events such as:<img src=“#” onerror= “alert(1)”/>
  5. CSS Cross Station:background-url
  6. Using character encoding


  1. xss-filter, filter Tags

2. httpOnly

  1. When exporting variables to a page, you need to code


Single system login

httpStateless protocol

The server processes each browser request separately

To authenticate browser requests, and because HTTP is a stateless protocol, the server and browser need to jointly maintain a state

Conversational mechanism

The browser requests the server for the first time, creates a session ID, and stores it by the browser. Each request will be brought later. After the server obtains it, it can judge whether it is the same user or not

Single system utilizationcookie

Logon status

When the browser requests the server for the first time, it needs to verify the user name and password. By comparing with those in the database, it can verify that the session is marked as “authorized”

Check the login status every time later

Single sign on (multi system login,single sign onsso)

Users can log in and log out once, and get results in multiple systems

Due to the different domains of multiple systems, all cookies will be limited and sent by the browserhttpMatching with this domain will be carried automatically on requestcookie, not allcookie

If willdomainSetting to a top-level domain name has restrictions:

  1. System group domain name unification
  2. Each system uses the same technology
  3. cookieUnsafe

Sign in

Compared to single system login,ssoThere is an additional authentication center. Only the authentication center accepts security information such as user name and password. Other systems do not provide login access, only accept indirect authorization from the authentication center. Indirect authorization is realized by token,ssoThe authentication center can verify the user’s user name and password, and create an authorization token. In the next jump process, the authorization token is sent to each subsystem as a parameter. When the subsystem gets the token, it is authorized to create a local session. The login mode of the local session is the same as that of the single system. This process, that is, the principle of single sign on, is illustrated by the following figure

Session and login mechanism

After successful login, the user will establish a session with SSO authentication center and each subsystem. The session established by the user with SSO authentication center is called global session, and the session established by the user with each subsystem is called local session. After the establishment of local session, the user accessing the protected resources of the subsystem will no longer pass SSO authentication center


Session and login mechanism

Specific jump

Suppose the URLs of the authentication center and system 2、system2.comVisitsystem2.comJump to because you are not logged, jump address: additional information is needed), and it becomes the browser andhttp://sso.comThe session between sites has been marked as logged in for the reason of system 1 logging in, so the authentication center takes a token, hops back according to the service parameter, and attaches the token, and the hop back address is:

How to verify login information

  1. Between different domains

    • When you log in to a system, you must jump to another system and set cookies
    • Nodejs realizes 302 jump
  2. Different sites with the same domain name

    • Sharecookie
  3. Same domain, different subdomains

    • DepositsessionIdThe domains of are all higher level


Recommended Today

Sharing 10 useful methods of laravel 5.8 sets

This article is forwarded from the professional laravel developer community, original link:… In laravel, there is a very useful class for manipulating arrays, called collections. I believe that every developer of laravel has used the collection more or less, especially when operating eloquent. In this article, I will list 10 common methods. 1. Weight […]