How to save and retrieve session from Redis

前端 未结 3 1609
无人及你
无人及你 2020-12-07 17:57

I am trying to integrate Redis sessions into my authentication system written in Node.js.

I have been able to successfully set up Redis server, connect-redis

相关标签:
3条回答
  • 2020-12-07 18:03

    You can also use the Redis monitor tool to see all the action in real time! When you refresh your app you will see the data appear in the console window.

    redis-cli monitor
    

    Sample Output for Sessions using tj/connect-redis

    1538704759.924701 [0 unix:/tmp/redis.sock] "expire" "sess:F9x-YgbgXu1g7RG8tFlkwY3RV0JzHgCh" "3600"
    1538704759.131285 [0 unix:/tmp/redis.sock] "get" "sess:F9x-YgbgXu1g7RG8tFlkwY3RV0JzHgCh"
    1538704787.179318 [0 unix:/tmp/redis.sock] "set" "sess:Hl3LPbOBdKO44SG4zQHFn2gfdiWTwzWW" "{\"cookie\":{\"originalMaxAge\":3600000,\"expires\":\"2018-10-05T02:59:47.178Z\",\"secure\":true,\"httpOnly\":true,\"domain\":\".indospace.io\",\"path\":\"/\"},\"path\":\"/\",\"userAgent\":{\"family\":\"NewRelicPingerBot\",\"major\":\"1\",\"minor\":\"0\",\"patch\":\"0\",\"device\":{\"family\":\"Other\",\"major\":\"0\",\"minor\":\"0\",\"patch\":\"0\"},\"os\":{\"family\":\"Other\",\"major\":\"0\",\"minor\":\"0\",\"patch\":\"0\"}},\"ip\":\"184.73.237.85\",\"page_not_found_count\":0,\"city\":\"Ashburn\",\"state\":\"VA\",\"city_state\":\"Ashburn, VA\",\"zip\":\"20149\",\"latitude\":39.0481,\"longitude\":-77.4728,\"country\":\"US\"}" "EX" "3599"
    1538704787.179318 [0 unix:/tmp/redis.sock] "set" "sess:Hl3LPbOBdKO44SG4zQHFn2gfdiWTwzWW" "{\"cookie\":{\"originalMaxAge\":3600000,\"expires\":\"2018-10-05T02:59:47.178Z\",\"secure\":true,\"httpOnly\":true,\"domain\":\".indospace.io\",\"path\":\"/\"},\"path\":\"/\",\"userAgent\":{\"family\":\"NewRelicPingerBot\",\"major\":\"1\",\"minor\":\"0\",\"patch\":\"0\",\"device\":{\"family\":\"Other\",\"major\":\"0\",\"minor\":\"0\",\"patch\":\"0\"},\"os\":{\"family\":\"Other\",\"major\":\"0\",\"minor\":\"0\",\"patch\":\"0\"}},\"ip\":\"184.73.237.85\",\"page_not_found_count\":0,\"city\":\"Ashburn\",\"state\":\"VA\",\"city_state\":\"Ashburn, VA\",\"zip\":\"20149\",\"latitude\":39.0481,\"longitude\":-77.4728,\"country\":\"US\"}" "EX" "3599"
    
    0 讨论(0)
  • 2020-12-07 18:10

    That should be all there is to it. You access the session in your route handlers via req.session. The sessions are created, saved, and destroyed automatically.

    If you need to manually create a new session for a user, call req.session.regenerate().

    If you need to save it manually, you can call req.session.save().

    If you need to destroy it manually, you can call req.session.destroy().

    See the Connect documentation for the full list of methods and properties.

    0 讨论(0)
  • 2020-12-07 18:14

    Consider this code.

    var express = require('express');
    var redis   = require("redis");
    var session = require('express-session');
    var redisStore = require('connect-redis')(session);
    var bodyParser = require('body-parser');
    var client  = redis.createClient();
    var app = express();
    
    app.set('views', __dirname + '/views');
    app.engine('html', require('ejs').renderFile);
    
    app.use(session({
        secret: 'ssshhhhh',
        // create new redis store.
        store: new redisStore({ host: 'localhost', port: 6379, client: client,ttl :  260}),
        saveUninitialized: false,
        resave: false
    }));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}));
    
    app.get('/',function(req,res){  
        // create new session object.
        if(req.session.key) {
            // if email key is sent redirect.
            res.redirect('/admin');
        } else {
            // else go to home page.
            res.render('index.html');
        }
    });
    
    app.post('/login',function(req,res){
        // when user login set the key to redis.
        req.session.key=req.body.email;
        res.end('done');
    });
    
    app.get('/logout',function(req,res){
        req.session.destroy(function(err){
            if(err){
                console.log(err);
            } else {
                res.redirect('/');
            }
        });
    });
    
    app.listen(3000,function(){
        console.log("App Started on PORT 3000");
    });
    

    So you need to install connect-redis and pass your express-session instance to it.

    Then in middleware initialize redisStore with server details like this.

    app.use(session({
        secret: 'ssshhhhh',
        // create new redis store.
        store: new redisStore({ host: 'localhost', port: 6379, client: client,ttl :  260}),
        saveUninitialized: false,
        resave: false
    })); 
    

    I put ttl to 260, you can increase. After TTL reaches its limits, it will automatically delete the redis key.

    In routers you can use req.session variable to SET, EDIT or DESTROY the session.

    One more thing...

    If you want custom cookie i.e not as same as in your Redis store you can use cookie-parser to set cookie secrets.

    Hope it helps.

    link : https://codeforgeek.com/2015/07/using-redis-to-handle-session-in-node-js/

    0 讨论(0)
提交回复
热议问题