【问题标题】:Protect express.js endpoint with passport使用护照保护 express.js 端点
【发布时间】:2020-10-29 19:57:37
【问题描述】:

我想保护我的 express 应用程序中的一些端点,如果我的应用程序变成一个大应用程序,我想创建一些易于管理的东西......现在我正在做这样的事情:

setProtected(router) {
    const self = this;
    router.use(this.auth);
    ...
}


setPublic(router) {
    const self = this;
    ...
}


getRouter() {
    const router = express.Router();
    this.setPublic(router);
    this.setProtected(router);
    return router;
}

与:

  auth(req, res, next) {
    if(req.isAuthenticated()) {
      console.log('req.isAuthenticated()', req.isAuthenticated());
      return next();
    }
    return res.send(401);
  }

在这种情况下的问题是难以维护,并且如果我的 publicRoute 中有 /:id 并且例如 /my-items 在我的受保护路由中有 /my-items 时我没有登录并且我尝试到达 /my-items 我得到 /:id 的代码。

另一个想法是创建一个包含我所有 url 列表的 json,其中包含相同的信息,例如受保护/不受保护和最终角色,然后使用以下内容更改身份验证:

import urls from './urls';
auth(req, res, next) {
    if (urls[req.url] == 'public') {
        return next()
    } 
    else if (urls[req.url] == 'protected' && req.isAuthenticated()) {
        return next();
    }
    return res.send(401);
}

什么方法最适合你?

【问题讨论】:

    标签: node.js express authentication


    【解决方案1】:

    You can chain middlewares: 例如。

    const authenticate = (req, res, next) {
    .. some auth logic
    next();
    }
    
    app.use('/', main...
    app.use('/profile', authenticate, otherMiddleware, 
    app.use('/admin', authenticate, isAdmin, otherMiddleware... 
    

    【讨论】:

    • 我知道这一点,但可能我想在所有路由之前定义一些东西,而不是在所有路由中注入中间件......
    • app.use(authenticate);或 router.use(authenticate)
    • 试过了,但我无法获得 req.router.path 因为这还没有设置:(
    【解决方案2】:

    在您的主文件 (server.js) 中导入路由并在那里使用中间件 :)

    server.js

    const express = require('express')
    const cors = require('cors')
    const app = express()
    
    // import admin routes
    const adminRoute = require('./app/routes/admin.route.js')
    
    // Add middleware for parsing URL encoded bodies (which are usually sent by browser)
    app.use(cors())
    // Add middleware for parsing JSON and urlencoded data and populating `req.body`
    app.use(express.urlencoded({ extended: false }))
    app.use(express.json())
    
    
    // homepage route
    app.get("/", (req, res) => {
      res.json({ message: "Hello World" })
    })
    
    // restricted by middleware "isAdmin"
    app.use('/api/v1', isAdmin, adminRoute)
    
    app.listen(8008).on('listening', () => {
      console.log('Server is running on 8008')
    })
    

    admin.route.js

    const express = require('express')
    const admin = require('../controllers/admin.controller.js')
    
    const router = express.Router()
    
    // get all admin users
    router.get('/users', (req, res, next)  => {
      admin.getAdminUsers(req, res, next)
    })
    
    module.exports = router
    

    【讨论】:

      猜你喜欢
      • 2020-06-25
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多