preface

I have been using KOA2 for a long time, and remember that after koA was upgraded to 2, orthodox KOA-sessions did not support async/await, so I used koA-session2 and KOA-session2-mongo. Suddenly I went to Changelog and found that koA-session was finally supported (it has been supported for a long time, but not found), so I tried to use the KOA-session scheme.

Koa – session2 scheme

Scenario 1: Using memory as session storage

Writing:

const app = new Koa();
const session = require("koa-session2")
app.use(session({
    maxAge: 20 * 1000
}))
Copy the code

Resolution:

Koa-session2 stores session values in memory by default. If maxAge is set, Response Headers will have the set-cookie attribute when ajax requests or page requests are returned:

set-cookie:koa:sess=c6e924a48654bf7cd0b8828bf2537579449510e47408158a; path=/; expires=Thu, 25 Jan 2018 03:07:42 GMT; httponly
Copy the code

The browser will save a cookie whose Expires/ max-age property is set to maxAge: 2018-01-25T03:12:09.419z. Let’s look at server: When ctx.session is assigned, koA-session2 will store session confidence in memory (this.sessions), but as soon as the server restarts, the session will be released in memory, so the login information will be lost even if the user’s cookie is still valid. If the server is running for a long time and the time specified by maxAge is exceeded, the cookie in the browser will be cleared by the browser. Therefore, the Request Headers will not carry cookies when sending ajax requests or page requests: Cookies: koa: c14b75b54400f5569f5ca9b93fa50eb811b632a8070adb sess = 12, the server can’t get a Cookie can’t read session, although the session to can not read, However, koA-session2 will periodically delete expired session values stored in the memory according to the maxAge timer to ensure that the server memory will not burst. Of course, if maxAge is not set, the Expires/ max-age attribute value of the cookie stored in the browser is Session, which makes the cookie stored in the browser permanently valid (until the browser closes), and the cookie in the server will not be cleared periodically. When there is a lot of traffic, The server’s memory will burst.

Code parsing

Scenario 2: Use Mongo as session storage

Writing:

const session = require("koa-session2")
const MongoStore = require("koa-session2-mongo")
app.use(session({
    store: new MongoStore({
        url:  DB_URL  // your mongodb url  required
        collection: optional, db session collection name,default "__session"
    }),
    maxAge: 20 * 1000
}))
Copy the code

Resolution:

By using the KOA-session2-Mongo package, it is possible to save sessions to the Mongo database. Sessions are never lost, whether the server is restarted or not, as opposed to stored in memory, unless cookies expire. Minor bug: When maxAge is set, koa-session2-Mongo creates fields using maxAge to set the expireAfterSeconds property, which is a feature provided by Mongo that automatically deletes this record when it expires.

Koa – the session

Scenario 1: Using cookies

Writing:

const session = require("koa-session")
app.use(session({
    signed:false,
    maxAge: 20 * 1000
},app))
Copy the code

Resolution:

When assigning a session value, koA-session encrypts the session value and sets it to a cookie:

Request Headers:
set-cookie:koa:sess=eyJuYW1lIjoyLCJfZXhwaXJlIjoxNTE2ODUyNzI1MTM3LCJfbWF4QWdlIjoyMDAwMH0=; path=/; expires=Thu, 25 Jan 2018 03:58:45 GMT; httponly
Copy the code

It is up to the browser to control session expiration clearance. That is, if we store the password in session: CTX. Session. Password = 123, Session middleware will encrypt {password:123} (new Buffer(json.stringify ({password:123})).toString(‘base64’)) and return the cookie to the browser! This is a serious problem, and it can be easily cracked. Of course, the benefit of storing cookies is also great: even if the server restarts, the session will remain until it expires.

Scenario 2: Use mongo database to store sessions

Writing:

const session = require("koa-session")
const MongoStore = require("koa-session-mongo2")
app.use(session({
    store: new MongoStore({
        url:  DB_URL  // your mongodb url  required
        db:'user',
        collection: optional, db session collection name,default "__session"
        signed:false // if true, please set app.keys = ['... ']
    }),
    signed:false,
    maxAge: 20 * 1000
},app))
Copy the code

Resolution:

As koA-generic-session-mongo does not support async/await, use KoA-session-mongo2 as store middleware. When assigning a value to a session, koA-session will store the session in the Mongo database and then return it to the SID randomly generated by cookie. Cookie stores this SID. When issuing a request, the server will query the corresponding session value in MonGO according to the SID. Then assign ctx.session. Similarly, koA-session-Mongo2 does not have the function to delete outdated sessions, so the server needs to run a scheduled task to manually delete them.

In conclusion:

Use KOA-session + KOA-session-Mongo2 to realize the session storage is more convenient, for the use of token, reduce the process of sending token every request, suitable for some of the low security requirements of the project.