Node.js 개발 중인 쿠키 및 세션

5851 단어 expressnode.jskoa.js
쿠키
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은 서버에 저장된 세션입니다.세션의 전형적인 응용 장면은 사용자가 특정한 사이트에 로그인한 후에 로그인 정보를 세션에 넣고 이후의 매번 요청에서 해당하는 로그인 정보를 조회하여 해당 사용자의 합법성을 확보하는 것이다.예를 들어 카트 등 명장면 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.
세션을 사용하는 이유
세션은 일반적으로 웹 응용의 배경에서 웹 응용은 HTTP 프로토콜을 바탕으로 하는 것이고 HTTP 프로토콜은 바로 무상태 프로토콜이라는 것을 알 수 있다.즉, 사용자가 A페이지에서 B페이지로 이동하면 HTTP 요청을 다시 보내고, 서버는 응답을 되돌릴 때 해당 사용자가 B페이지를 요청하기 전에 무엇을 했는지 알 수 없다.바로 이런 웹 동태화의 수요는 HTTP 프로토콜에 어려운 문제를 제기했다. 무상태 프로토콜은 어떻게 해야 두 번의 연속적인 요청을 연결할 수 있습니까?즉 무상태 협의는 어떻게 해야만 유상태 수요를 만족시킬 수 있습니까?
이때 상태가 있는 것은 필연적인 추세이고 협의의 무상태성도 나무가 된 배이기 때문에 우리는 이 모순을 해결하고 HTTP 연결 상태를 유지하는 방안이 필요하다. 그래서 쿠키와session이 등장했다.
session과 쿠키의 관계
위에서 언급한 HTTP 프로토콜 자체의 무상태를 해결하는 방법으로는 쿠키와session이 있다.양자는 모두 상태를 기록할 수 있다. 전자는 상태 데이터를 클라이언트에 저장하고 후자는 서비스 측에 저장한다.
보안 쿠키는 정보를 클라이언트에 저장합니다. 만약에 암호화하지 않으면 일부 프라이버시 정보를 노출할 수 있습니다. 안전성이 매우 떨어집니다. 일반적으로 민감한 정보는 암호화를 거쳐 쿠키에 저장되지만 도난당하기 쉽습니다.한편,session은 정보만 서버에 저장할 수 있고 파일이나 데이터베이스에 저장하면 도둑맞을 수도 있다. 다만 cookie보다 가능성이 너무 적다.Session의 안전성에 있어 두드러진 것은 세션 납치 문제가 존재하는데 이것은 안전 위협이다. 전체적으로 보면session의 안전성은 쿠키보다 높다.
express 프레임워크의session 메모리 저장소
express-session은express 상자를 바탕으로session을 처리하는 중간부품입니다.session의 인증 메커니즘은 쿠키와 떨어질 수 없기 때문에 쿠키Parser 중간부품을 동시에 사용해야 한다.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.세션은 JSON 형식의 자바스크립트 대상입니다. 우리는 사용하는 과정에서 임의로 구성원을 추가할 수 있습니다. 이 구성원들은 자동으로 옵션 파라미터가 지정한 곳에 저장됩니다. 기본값은 메모리입니다.
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 StoreYou 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
  • api needs to return a Promise, Thunk or generator.

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

  • koa-rediskoa-redis works with koa-generic-session (a generic session middleware for koa).
    Events
  • ready
  • connect
  • reconnecting
  • error
  • end
  • warning

  • node_rediscookies와session이 사용자 상태를 기록하는 메커니즘
    For a full list of cookie options see expressjs/cookies

    좋은 웹페이지 즐겨찾기