Exercise 16 - Express Session - P1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Express Session (Part 1)

Objectives and Outcomes


In this exercise you will use Express sessions to track authenticated users so as to enable
authenticated access to server resources. At the end of this exercise you will be able to:

 Set up your Express server to use Express sessions to track authenticated users
 Enable clients to access secure resources on the server after authentication.
Installing express-session

 Still in the conFusionServer folder, install express-session and session-file-store Node modules
as follows:

npm install express-session session-file-store

Using express-session

 Then, update app.js as follows to use Express session:

 ...

var session = require('express-session');

var FileStore = require('session-file-store')(session);

 ...

app.use(session({

name: 'session-id',

secret: '12345-67890-09876-54321',

saveUninitialized: false,

resave: false,

store: new FileStore()

}));

function auth (req, res, next) {

console.log(req.session);

if (!req.session.user) {

var authHeader = req.headers.authorization;

if (!authHeader) {

1
var err = new Error('You are not authenticated!');

res.setHeader('WWW-Authenticate', 'Basic');

err.status = 401;

next(err);

return;

var auth = new Buffer.from(authHeader.split(' ')[1], 'base64').toString().split(':');

var user = auth[0];

var pass = auth[1];

if (user == 'admin' && pass == 'password') {

req.session.user = 'admin';

next(); // authorized

} else {

var err = new Error('You are not authenticated!');

res.setHeader('WWW-Authenticate', 'Basic');

err.status = 401;

next(err);

else {

if (req.session.user === 'admin') {

console.log('req.session: ',req.session);

next();

else {

var err = new Error('You are not authenticated!');

err.status = 401;

next(err);

}
2

 ...

 Save the changes, run the server and examine the behavior.
Conclusions
In this exercise you set up the Express server to use express-session to track authenticated users to
provide access to secure resources.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy