【问题标题】:Express: basic authentication for one routeExpress:一条路由的基本认证
【发布时间】:2014-07-13 01:37:07
【问题描述】:

我正在尝试制作一组​​工具来访问我的数据库。大多数都与通过我的网络应用程序访问数据有关,但我还需要我的 express 站点的一个页面,其中包含站点所有者的密码,以提供用于编辑数据库的在线工具;所有其他路线都不需要身份验证。

使用 express 3,basic-auth 使添加这样的密码变得容易,但由于 Express 4 中的中间件和大多数在线教程已过时,其功能已被削弱。新版basic-auth会处理认证头信息,但是如何在浏览器中触发登录弹窗

下面的代码只是样板文件,因此欢迎提供世界上最简单的登录提示。

express = require('express')
app = express()
auth = require 'basic-auth'


port = Number(process.env.PORT || 9778);
app.listen port, () ->
    console.log "Listening on port: " + port


app.use '/editor', (req, res) ->
    user = auth req
    if (user == "....") ...
    console.log user


app.get '/editor', (req, res) ->
    # if authenticated send 'editor.html' else....
    res.send 401, "Need password"

目前我正在添加身份验证以访问页面,然后允许该页面发布到 CRUD 节点。我认为我真的应该转向适当的 REST API 并要求在 CUD 上进行身份验证?

【问题讨论】:

    标签: javascript node.js authentication express


    【解决方案1】:

    根据Basic Authentication 规范,服务器可以通过发送带有401 状态码的WWW-Authenticate 标头来请求身份验证。以下对我有用:

    res.set({
      'WWW-Authenticate': 'Basic realm="simple-admin"'
    }).send(401);
    

    我把它放在我自己的中间件中,看起来像这样:

    var auth = require('basic-auth');
    
    module.exports = function(req, res, next){
      var user = auth(req);
      if(validAuth){ // Here you need some logic to validate authentication
        next();
      } else {
        res.set({
          'WWW-Authenticate': 'Basic realm="simple-admin"'
        }).send(401);
      }
    };
    

    【讨论】:

      【解决方案2】:

      基于@JustinY,这是最终结果

      app.use '/editor', (req, res, next) ->
          user = auth req
          if (user.pass == '******')
              console.log user
              next()
          else
              res.set
                  'WWW-Authenticate': 'Basic realm="simple-admin"'
              res.send 401, "Need password"
      
      
      app.get '/editor', (req, res) ->
          res.sendfile 'editor/index.html'
      

      【讨论】:

        猜你喜欢
        • 2016-10-31
        • 1970-01-01
        • 2015-07-17
        • 1970-01-01
        • 2016-03-12
        • 2017-09-05
        • 2015-12-17
        • 2015-07-31
        • 2015-07-12
        相关资源
        最近更新 更多