Node.js開發中的Cookie和Session

什麼是cookie

A cookie is a small piece of text stored on a user's computer by their browser. Common uses for cookies are authentication, storing of site preferences, shopping cart items, and server session identification.html

Each time the users' web browser interacts with a web server it will pass the cookie information to the web server. Only the cookies stored by the browser that relate to the domain in the requested URL will be sent to the server. This means that cookies that relate to www.example.com will not be sent to www.exampledomain.com.node

In essence, a cookie is a great way of linking one page to the next for a user's interaction with a web site or web application.git

什麼是session

session是保存在服務器端的會話。session的典型應用場景是用戶登陸某網站以後,將其登陸信息放入session,在之後的每次請求中查詢相應的登陸信息以確保該用戶合法。好比購物車等等經典場景
To store information that is not appropriate to store client-side, we use sessions. Lasso has built in session handling, and deals with the setting and retrieval of the cookie itself. It will automatically set and retrieve the session id, which is the only thing stored client-side.github

爲何要使用session

談及session通常是在web應用的背景之下,咱們知道web應用是基於HTTP協議的,而HTTP協議偏偏是一種無狀態協議。也就是說,用戶從A頁面跳轉到B頁面會從新發送一次HTTP請求,而服務端在返回響應的時候是沒法獲知該用戶在請求B頁面以前作了什麼的。
而正是這種web動態化的需求,給HTTP協議提出了一個難題:一個無狀態的協議怎樣才能關聯兩次連續的請求呢?也就是說無狀態的協議怎樣才能知足有狀態的需求呢?web

此時有狀態是必然趨勢而協議的無狀態性也是木已成舟,所以咱們須要一些方案來解決這個矛盾,來保持HTTP鏈接狀態,因而出現了cookie和session。redis

session與cookie的關係

上面提到解決HTTP協議自身無狀態的方式有cookie和session。兩者都能記錄狀態,前者是將狀態數據保存在客戶端,後者則保存在服務端。數據庫

安全性
cookie將信息保存在客戶端,若是不進行加密的話,無疑會暴露一些隱私信息,安全性不好,通常狀況下敏感信息是通過加密後存儲在cookie中,但很容易就會被竊取。而session只會將信息存儲在服務端,若是存儲在文件或數據庫中,也有被竊取的可能,只是可能性比cookie小了太多。
Session安全性方面比較突出的是存在會話劫持的問題,這是一種安全威脅,整體來說,session的安全性要高於cookie。express

express框架之session 內存存儲

express-session 是基於express框專門用於處理session的中間件。session的認證機制離不開cookie,須要同時使用cookieParser 中間件。
https://www.npmjs.com/package...npm

var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');

var app = express();

app.use(cookieParser());
app.use(session({
    secret: '12345',
    name: 'testapp',   //這裏的name值得是cookie的name,默認cookie的name是:connect.sid
    cookie: {maxAge: 80000 },  //設置maxAge是80000ms,即80s後session和相應的cookie失效過時
    resave: false,
    saveUninitialized: true,
}));


app.get('/awesome', function(req, res){
    
    if(req.session.lastPage) {
        console.log('Last page was: ' + req.session.lastPage + ".");    
    }    
    req.session.lastPage = '/awesome'; //每一次訪問時,session對象的lastPage會自動的保存或更新內存中的session中去。
    res.send("You're Awesome. And the session expired time is: " + req.session.cookie.maxAge);
});

app.get('/radical', function(req, res){
    if (req.session.lastPage) {
        console.log('Last page was: ' + req.session.lastPage + ".");    
    }
    req.session.lastPage = '/radical';  
    res.send('What a radical visit! And the session expired time is: ' + req.session.cookie.maxAge);
});

app.get('/tubular', function(req, res){
    if (req.session.lastPage){
        console.log("Last page was: " + req.session.lastPage + ".");    
    }

    req.session.lastPage = '/tubular';
    res.send('Are you a suffer? And the session expired time is: ' + req.session.cookie.maxAge);
});


app.listen(5000);

 一旦咱們將express-session中間件用use掛載後,咱們能夠很方便的經過req參數來存儲和訪問session對象的數據。req.session是一個JSON格式的JavaScript對象,咱們能夠在使用的過程當中隨意的增長成員,這些成員會自動的被保存到option參數指定的地方,默認即爲內存中去。api

Koa框架之session 內存存儲

var session = require('koa-generic-session');
var redisStore = require('koa-redis');
var koa = require('koa');

var app = new koa(); // for koa v1 use `var app = koa();`
app.keys = ['keys', 'keykeys'];
app.use(session({
  store: redisStore()
}));

cookie: session cookie settings, defaulting to

{
  path: '/',
  httpOnly: true,
  maxAge: 24 * 60 * 60 * 1000 //one day in ms,
  rewrite: true,
  signed: true
}

if you setcookie.maxAge to null, meaning no "expires" parameter is set so the cookie becomes a browser-session cookie. When the user closes the browser the cookie (and session) will be removed.

Notice that ttl is different from cookie.maxAge, ttl set the expire time of sessionStore. So if you set cookie.maxAge = null, and ttl=ms('1d'), the session will expired after one day, but the cookie will destroy when the user closes the browser. And mostly you can just ignore options.ttl, koa-generic-session will parse cookie.maxAge as the tll

Session Store
You can use any other store to replace the default MemoryStore, it just needs to follow this api:

  • get(sid): get session object by sid
  • set(sid, sess, ttl): set session object for sid, with a ttl (in ms)
  • destroy(sid): destroy session for sid
  1. api needs to return a Promise, Thunk or generator.

And use these events to report the store's status.

  • connect
  • disconnect

koa-redis
koa-redis works with koa-generic-session (a generic session middleware for koa).

Events

  • ready
  • connect
  • reconnecting
  • error
  • end
  • warning

node_redis
cookies和session記錄用戶狀態的機制

For a full list of cookie options see expressjs/cookies

相關文章
相關標籤/搜索