用护照保护express.js端点

时间:2018-03-18 13:34:20

标签: node.js express authentication

我想在我的快递应用程序中保护一些端点,如果我的应用程序成为一个大应用程序,我想创建一些简单的管理...现在我做这样的事情:

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我得到/:id。

的代码

另一个想法是创建一个json,其中包含所有url的列表,其中包含相同的信息,如protected / not protected和eventual roles,然后使用类似的内容更改auth:

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);
}

最适合你的方式是什么?

2 个答案:

答案 0 :(得分:0)

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... 

答案 1 :(得分:0)

在您的主文件(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
相关问题