2

我有一个简单的应用程序,它有一个登录页面和一个用于经过身份验证的用户的部分,未经身份验证的用户从中被重定向回登录。在我所有的路线结束时,我有app.all('*', ...)返回 404 错误页面。

当我通过身份验证时,一切正常,但如果我注销并尝试获取不存在的路由,我将被重定向到登录页面,而不是得到 404 响应。

我知道这是因为我添加了处理重定向的中间件,但我希望它只能在那个确切的路由器中指定的路由上工作 - 而不是在中间件之后放置的所有路由(甚至是应用程序级的路由)中。

我目前看到的唯一解决方案是在每个受限路由中使用这个 authCheck 中间件,而不是使用全局注册它,router.use但我仍然想知道是否有更好的方法?

const express = require('express')

module.exports = (app) => {
  const authRouter = express.Router()

  // ================================
  // ========= Public Routes ========
  // ================================
  app.get('/login', () => { /* ... login route */ })
  app.post('/login', () => { /* ... login route */ })

  // ====================================
  // ========= Restricted Routes ========
  // ====================================
  authRouter.use((req, res, next) => {
    req.isAuthenticated()
      ? next()
      : res.redirect('/login')
  })

  authRouter.get('/', () => { /* restricted route */ })

  // register restricted routes
  app.use(authRouter)

  // ========================================
  // ============ Other routes ==============
  // ========================================

  // error 404 route <--- this works only for authenticated users
  app.get('*', (req, res) => {

    res.status(404)
    res.render('error404')
  })
}

感谢您的任何想法..

4

3 回答 3

0

试试这个,你可以创建一个没有身份验证的所有 URL 的数组并检查中间件内部。

const authMiddleware = (req, res, next) => {
    /* Urls Without Auth */
    const withoutAuth = ['/login'];
    if (withoutAuth.includes(req.url) || req.isAuthenticated()) {
        next();
    } else {
        res.redirect('/login');
    }
};

app.use(authMiddleware);
于 2018-03-07T15:22:51.093 回答
0
const express = require('express')
// Note: FWIW I think it's better to organize your middleware
// into separate files and store them into separate directory
// So you could use it like that:
// const verifyAuthMiddleware = require('./middleware/verifyAuthMiddleware);
const verifyAuthMiddleware = (req, res, next) => {
    req.isAuthenticated()
      ? next()
      : res.redirect('/login')
  };

module.exports = (app) => {    
  // ================================
  // ========= Public Routes ========
  // ================================
  app.get('/login', () => { /* ... login route */ })
  app.post('/login', () => { /* ... login route */ })

  // ====================================
  // ========= Restricted Routes ========
  // ====================================    
  // You can add the middleware like that
  app.get('/', [verifyAuthMiddleware], () => { /* restricted route */ });

  // Or you can add a middleware to a group of routes like that
  app.use('/user', [verifyAuthMiddleware]);
  // And then every route that starts with "/user" uses the middleware
  app.get('/user/settings', () => {});
  app.get('/user/wallet', () => {});
  app.get('/user', () => {});
  app.post('/user/wallet', () => {});
  // etc


  // ========================================
  // ============ Other routes ==============
  // ========================================

  // error 404 route <--- this works only for authenticated users
  app.get('*', (req, res) => {

    res.status(404)
    res.render('error404')
  })
}
于 2018-03-07T16:18:52.893 回答
0

谢谢您的回复。最后,我这样做了:

function authCheck (req, res, next) {
    return req.isAuthenticated()
        ? next()
        : res.redirect('/login')
}

// Product routes
const prodRouter = express.Router()
prodRouter.get('/', products.getlist)
prodRouter.get('/:uuid/:tab?', products.getbyId)
prodRouter.post('/:uuid/:tab?', products.update)

// Register product routes
app.use('/products', [authCheck, prodRouter])

// For all other routes return 404 error page
app.get('*', (req, res) => {
    res.status(404).render('error404')
})

使用这种方法,authCheck中间件仅用于/product路由,因此当我访问时,/missing-page我可以正确获取Error 404 page.

于 2018-05-30T11:30:55.803 回答