Basic HTTP authentication with Node and Express 4

后端 未结 9 2088
萌比男神i
萌比男神i 2020-11-29 15:48

It looks like implementing basic HTTP authentication with Express v3 was trivial:

app.use(express.basicAuth(\'username\', \'password\'));

V

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 16:38

    Express has removed this functionality and now recommends you use the basic-auth library.

    Here's an example of how to use:

    var http = require('http')
    var auth = require('basic-auth')
    
    // Create server
    var server = http.createServer(function (req, res) {
      var credentials = auth(req)
    
      if (!credentials || credentials.name !== 'aladdin' || credentials.pass !== 'opensesame') {
        res.statusCode = 401
        res.setHeader('WWW-Authenticate', 'Basic realm="example"')
        res.end('Access denied')
      } else {
        res.end('Access granted')
      }
    })
    
    // Listen
    server.listen(3000)
    

    To send a request to this route you need to include an Authorization header formatted for basic auth.

    Sending a curl request first you must take the base64 encoding of name:pass or in this case aladdin:opensesame which is equal to YWxhZGRpbjpvcGVuc2VzYW1l

    Your curl request will then look like:

     curl -H "Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l" http://localhost:3000/
    

提交回复
热议问题