简体   繁体   中英

How to make Express routes require authentication by default?

I've seen many examples of how to add an authentication middleware to certain routes that need to be restricted to logged-in users (implying that the default is to allow anyone to access pages), but I can't tell how to make all routes by default require being logged-in, and selectively choose certain routes among those that should be available to anonymous users.

Any ways to make it work like this? I'm using Express 4.

I would use: https://github.com/expressjs/session once the user is authenticated then you can check for valid sessions in your controller that handles the route of express.

Updated Answer

This is how I would do the control user logged

/**
 * Module dependencies
 */

var express = require('express'),
  http = require('http'),
  session = require('express-session'),
  app = module.exports = express();

/**
 * Configuration
 */

// all environments
app.set('port', process.env.PORT || 3000);
app.set('trust proxy', 1);
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: {
    secure: true
  }
}));


function checkUserLoggedIn(req, res, next) {
  return req.session;
}
/**
 * Routes to control by default is logged in with a regular expression
 */
app.get('/user/:use_id/*', function (req, res, next) {
  if (checkUserLoggedIn(req)) {
    console.log('User logged');
    next();
  } else {
    console.log('error');
  }
});
/**
 * User Home
 */
app.get('/user/:use_id/home/', function (req, res, next) {
  if (checkUserLoggedIn(req)) {
    console.log('User logged goes to home');
    next();
  } else {
    console.log('error');
  }
});


/**
 * Home for user that is actually logged
 */
app.get('/guest/dashboard', function (req, res, next) {
  console.log('This is guest dashboard');
});

/**
 * Home for user that is actually logged
 */
app.get('/guest/home', function (req, res, next) {
  console.log('This is guest home');
});


/**
 * Start Server
 */
http.createServer(app).listen(app.get('port'), function () {
  console.log('Express server listening on port ' + app.get('port'));
});

Then run

$ node app.js

Go to browser and access http://localhost:3000/home

The regular expression you defined in to control '/*' is getting all the defaults routing and then is going to the next route that matches, thats /home.

This is one way to do it, may be there is a better and more clear way to fit the issue. In the regular expression you control what you mean with default routes and for each case particular.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM