Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  40] [ 3]  / answers: 1 / hits: 22156  / 11 Years ago, sun, january 19, 2014, 12:00:00

I've seen many variations of this question, but none seemed to solve my issue. I'm trying to set up a Node.js server using Express. Here is my server configuration:



var express = require('express'),
RedisStore = require('connect-redis')(express);

var app = express();

app.use(express.urlencoded());
app.use(express.json());
app.use(express.cookieParser());
app.use(express.session({
store: new RedisStore(),
secret: APP_SECRET
}));

// Initialize redis connection
var client = redis.createClient();
client.on('connect', function() {
console.log('Connected to Redis server')
})
client.on('error', function (err) {
console.log('Error ' + err);
});

// Enable cross-origin resource sharing
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
next();
});

var api = require('./controllers/api.js');

app.post('/login', api.login);
app.get('/auth', api.auth);

app.listen(3000);


And here are some simple routes:



exports.login = function(req, res) {
var user = new User(req.username, req.password);
req.session.user = user;
console.log(req.session.user); //works
res.json({user:user});
}

exports.auth = function(req, res) {
console.log(req.session.user); //doesn't work
res.json(req.session.user);
}


So in my login route, I can print the session variable as expected. But if I visit the auth route after visiting the login route, the session variable is undefined. How can I get Express sessions to work?


More From » node.js

 Answers
19

In a typical web application, the credentials used to authenticate a user will only be transmitted during the login request. If authentication succeeds, a session will be established and maintained via a cookie set in the user's browser.



Each subsequent request will not contain credentials or all user data, but rather the unique cookie that identifies the session. In order to support login sessions, You have to serialize and deserialize user instances to and from the session in every request.



In your case, you have assigned req.session.user = user; only in /login request. It will not be available for further requests(/auth).



You have to get user information in /auth request too by session id. (Or) Better you can use passport for authentication.


[#73074] Friday, January 17, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayaw

Total Points: 749
Total Questions: 88
Total Answers: 86

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
tayaw questions
;