什么是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.

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.

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.

什么是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.

为什么要使用session

谈及session一般是在web应用的背景之下,我们知道web应用是基于HTTP协议的,而HTTP协议恰恰是一种无状态协议。也就是说,用户从A页面跳转到B页面会重新发送一次HTTP请求,而服务端在返回响应的时候是无法获知该用户在请求B页面之前做了什么的。
而正是这种web动态化的需求,给HTTP协议提出了一个难题:一个无状态的协议怎样才能关联两次连续的请求呢?也就是说无状态的协议怎样才能满足有状态的需求呢?

此时有状态是必然趋势而协议的无状态性也是木已成舟,因此我们需要一些方案来解决这个矛盾,来保持HTTP连接状态,于是出现了cookie和session。

session与cookie的关系

上面提到解决HTTP协议自身无状态的方式有cookie和session。二者都能记录状态,前者是将状态数据保存在客户端,后者则保存在服务端。

安全性
cookie将信息保存在客户端,如果不进行加密的话,无疑会暴露一些隐私信息,安全性很差,一般情况下敏感信息是经过加密后存储在cookie中,但很容易就会被窃取。而session只会将信息存储在服务端,如果存储在文件或数据库中,也有被窃取的可能,只是可能性比cookie小了太多。
Session安全性方面比较突出的是存在会话劫持的问题,这是一种安全威胁,总体来讲,session的安全性要高于cookie。

express框架之session 内存存储

express-session 是基于express框专门用于处理session的中间件。session的认证机制离不开cookie,需要同时使用cookieParser 中间件。
https://www.npmjs.com/package...

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参数指定的地方,默认即为内存中去。

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

你可能感兴趣的文章

载入中...
老毛 老毛

80 声望

发布于专栏

web开发总结

不积跬步无以至千里

3 人关注