简体   繁体   English

在传递基本身份验证凭据时出现 axios 上的身份验证错误

[英]Getting authentication error on axios while passing basic authentication credentials

I've handled my server side's basic auth with nodejs, Please refer the code below.我已经用 nodejs 处理了我的服务器端的基本身份验证,请参考下面的代码。

module.exports = basicAuth;
// require("dotenv").config({ path: "./.env" });
require("dotenv/config");

// async function basicAuth(req, res, next) {
function basicAuth(req, res, next) {
  // check for basic auth header
  if (
    !req.headers.authorization ||
    req.headers.authorization.indexOf("Basic ") === -1
  ) {
    return res.status(401).json({ message: "Missing Authorization Header" });
  }

  console.log(req.headers.authorization);
  // verify auth credentials
  const base64Credentials = req.headers.authorization.split(" ")[1];
  //   console.log(base64Credentials);
  const credentials = Buffer.from(base64Credentials, "base64").toString(
    "ascii"
  );
  const [username, password] = credentials.split(":");
  // const user = await userService.authenticate({ username, password });
  let user = 0;
  if (
    username == process.env.API_USERNAME &&
    password == process.env.API_PASSWORD
  ) {
    user = 1;
  }
  if (!user) {
    return res
      .status(401)
      .json({ message: "Invalid Authentication Credentials" });
  }

  next();
}

I've added app.use(cors()) in my app.js and I'm able to access all routes using basic authentication.我在 app.js 中添加了app.use(cors())并且我能够使用基本身份验证访问所有路由。 I've written my front end application using react and I'm using axios to fetch the data using the routes that I created.我已经使用 react 编写了前端应用程序,并且正在使用 axios 使用我创建的路由来获取数据。 Please note the same API's work when I try to access it without using basic auth.当我尝试在不使用基本身份验证的情况下访问它时,请注意相同的 API 的工作。 Below is the code for accessing data using axios.下面是使用 axios 访问数据的代码。

try {
      require("dotenv").config();
      console.log(this.state.params);
      let urlparam = "http://localhost:5000/users/" + this.state.params;

      let result;
      result = await axios({
        url: "http://localhost:5000/users",
        method: "get",
        withCredentials: true,
        headers: {
          authorization: "Basic c2Fsb29uOnNhbG9vbg==",
        },
      });
    } catch (err) {
      console.log(err);
    }

Using the above code I get: The requested resource requires user authentication.使用上面的代码我得到:请求的资源需要用户身份验证。 on Edge browser and on Google chrome I get the error: Access to XMLHttpRequest at ' http://localhost:5000/users ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. on Edge browser and on Google chrome I get the error: Access to XMLHttpRequest at ' http://localhost:5000/users ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: Response to preflight request doesn '不通过访问控制检查:请求的资源上不存在'Access-Control-Allow-Origin' header。 and xhr.js:178 GET http://localhost:5000/users net::ERR_FAILEDxhr.js:178 GET http://localhost:5000/users net::ERR_FAILED

Please bear in mind I've added and used the cors middleware for all routes and it was working previously.请记住,我已经为所有路由添加并使用了 cors 中间件,它以前可以正常工作。 I even tried passing auth parameters separately like我什至尝试单独传递身份验证参数,例如

auth:{username:"",password:""}

it still wont work它仍然无法正常工作

I had to include app.use(basicAuth) below app.use(cors()) in the app.js file.我必须在 app.js 文件中的app.use(cors()) app.use(basicAuth)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 axios GET 调用不适用于基本身份验证? - Why axios GET call not working for basic authentication? 来自Javascript的Spring基本身份验证凭证 - Spring basic authentication credentials from Javascript 使用JavaScript捕获基本身份验证凭据 - Capture Basic Authentication Credentials Using JavaScript javascript中出现未经授权的错误,如何在angularjs中处理基本身份验证 - getting unauthorized error in javascript, how to handle basic authentication in angularjs ElectronJS Vue Axios基本身份验证访问控制-允许-起源错误 - ElectronJS Vue Axios Basic Authentication Access-Control-Allow-Origin error 使用HapiJS获取身份验证错误 - Getting authentication error with HapiJS 如何为fetch API继承基页的基本身份验证凭据? - How to inherit Basic Authentication credentials of the base page for the fetch API? 如何将用户重定向到其他服务器并包含HTTP基本身份验证凭据? - How to redirect a user to a different server and include HTTP basic authentication credentials? IE不要求正文中受保护资源的基本身份验证凭据 - IE not asking basic authentication credentials for a protected resource in body 如何处理 axios 中的 401(身份验证错误)并做出反应? - How to handle 401 (Authentication Error) in axios and react?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM