【问题标题】:NodeJS user authentication middlewareNodeJS 用户认证中间件
【发布时间】:2017-10-26 01:55:29
【问题描述】:

我想为应用程序创建用户身份验证中间件。我不会使用数据库中的任何数据进行此身份验证。假设,

var user = "me";
function authme(){
 //condition}

我将在我的路由器中使用“authme”作为中间件。

app.post('/api', authme, function(res, req){
})

我想以某种方式编写 authme 函数,以便当 user=me 时,它​​会路由此 api。我知道这是非常基本的,但我无法做到这一点。 先感谢您。

【问题讨论】:

    标签: node.js authentication middleware


    【解决方案1】:

    我假设您将在请求正文中收到用户的登录凭据。

    你的函数“authme”应该看起来像这样......

    /*
       Sample request body which you will receive from the client
       {
           "userId":"me",
           "password":"password"
       }
    */    
    function authme(req,res,next){
        if(req.body.userId=="me" && req.body.password=="random_password"){
            console.log("User authenticated");
            next(); 
        }
        else{
            console.log("Wrong authentication");
            res.sendStatus(401);
        }
    }
    
    app.post('/api', authme, function(req,res){
         //the user has been authenticated. 
    })
    

    【讨论】:

      猜你喜欢
      • 2018-08-25
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      相关资源
      最近更新 更多