如何在node.js中使用基本身份验证从url中获取用户名和密码

How to fetch username and password from url using basic authentication in node.js?

本文关键字:获取 url 用户 密码 身份验证 node js      更新时间:2023-09-26

我需要获得浏览器从url发送到node.js应用程序的用户名和密码。

我翻遍了各种文件和物品,但找不到任何有用的东西。有人知道怎么做吗?使用身份验证标头不是一个选项,因为现代Bowser不会设置它们。

https://username:password@myurl.com/
        =================
//         /'
//         ||
// I need this part

谢谢你的帮助!

这种身份验证方法称为"基本身份验证"。您可以使用以下代码通过basic-auth npm包访问用户名和密码:

const express = require('express');
const basicAuth = require('basic-auth');
let app = express();
app.get('/', function (req, res) {
    let user = basicAuth(req);
    console.log(user.name); //prints username
    console.log(user.pass); //prints password
});
app.listen(3000, function () {});

现在,如果您向http://username:password@localhost:3000/发送请求,此代码将在控制台中打印您的用户名和密码。

请注意,大多数浏览器都不支持这种身份验证方法。

IE或Chrome不再支持http://username:password@example.com格式,如果其他人还没有效仿,也不会感到惊讶。

(此处来自T.J.Crowder评论)

username:password作为base64编码的字符串包含在Authorization标头中:

http.createServer(function(req, res) {
  var header = req.headers['authorization'] || '',        // get the header
      token = header.split(/'s+/).pop()||'',            // and the encoded auth token
      auth = new Buffer(token, 'base64').toString(),    // convert from base64
      parts=auth.split(/:/),                          // split on colon
      username=parts[0],
      password=parts[1];
  res.writeHead(200,{'Content-Type':'text/plain'});
  res.end('username is "'+username+'" and password is "'+password+'"');
}).listen(1337,'127.0.0.1');

请看这篇文章:Node.JS中的基本HTTP身份验证?

这正是您想要的:

http://nodejs.org/api/url.html

如果你想知道从哪里获得URL本身,它会在请求对象中传递,也称为"路径":

Node.js:从请求中获取路径

/createserver/:username/:password
let params={
userName:req.params.username,
password:req.params.password
}
console.log(params);

这是你想要的吗。?

服务器可以访问请求对象中的URL:

http.createServer(function(req, res) {
    var url = req.url
    console.log(url) //echoes https://username:password@myurl.com/
    //do something with url
}).listen(8081,'127.0.0.1');