【问题标题】:401 (Unauthorized) ReactJS401(未经授权)ReactJS
【发布时间】:2018-05-19 10:12:06
【问题描述】:

我在这里遇到了一个问题,我正在使用 ReactJS 开发一个 Rest API 和一个 Web 应用程序。我正在尝试向 Rest API 发出 fetch 请求,但总是收到一个 401 代码,表示未经授权的访问。我在以下代码中发送fetch request

  SubmitClick(){

    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    } else {
      //console.log(this.state); //debug only
      fetch('http://localhost:4000/users/', {
        method: 'POST',
        headers: {
          'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          first_name: this.state.first_name,
          last_name: this.state.last_name,
          personal_phone: this.state.personal_phone,
          password: this.state.password
        })
      }).then(this.props.history.push('/get'));  //change page layout and URL
    }
  }

如您所见,我在请求中按照以下结构插入了 Authorization 标头:('Authorization' : 'Basic ' + encoding)。我从 Postman 软件的请求中获得了编码值。

这是我的 Rest API 的代码,我在其中配置了允许的用户和密码:

const express =     require('express');
const bodyParser =  require('body-parser');
const mongoose =    require('mongoose');
var basicAuth =     require('express-basic-auth')

const app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

mongoose.connect('mongodb://localhost/usersregs', { useMongoClient: true });
mongoose.Promise = global.Promise;

app.use(basicAuth({
    users: {
        'admin': 'supersecret',
        'adam': 'password1234',
        'eve': 'asdfghjkl'
    }
}))

app.use(bodyParser.json());

app.use(function(err, req, res, next){
    console.log(err);
    //res.status(450).send({err: err.message})
});

app.use(require('./routes/api'));  

app.listen(4000, function(){
    console.log('Now listening for request at port 4000');
}); 

使用谷歌浏览器开发者工具,我可以看到这个操作中的请求头,as you can see here

如果我删除了配置用户和密码的部分代码(在 Rest API 中),以及配置授权标头(Web 应用程序)的部分,则代码可以正常工作。我无法使其与 Authorization 标头一起使用。

我应该如何处理 fetch 请求中的 Authorization 标头,以便我可以访问 Rest API?

【问题讨论】:

标签: reactjs http-headers authorization fetch


【解决方案1】:

看起来问题与您正在使用的 express-basic-auth 模块有关。看这部分documentation

中间件现在将检查传入请求以匹配凭据 admin:supersecret

中间件将检查传入请求的基本身份验证 (Authorization) 标头,解析它并检查凭据是否合法。如果有任何凭据,则将在请求中添加一个 auth 属性,其中包含具有用户和密码属性的对象,并填充凭据,无论它们是否合法。

该文档没有提及关于 Authorization 标头的 Basic + encoding 的任何内容。您应该尝试使用 admin:supersecret 作为 Authorization 标头的值。

更新:

我认为您在滥用该模块。 express-basic-auth 似乎只是用于确保您已通过身份验证并允许您通过 API 获取信息。它在服务器中具有硬编码的用户/密码凭据,这似乎不允许以您使用的方式进行注册。包装说明说,

用于 Express 的简单即插即用 HTTP 基本身份验证中间件。

所以它只是 HTTP 基本身份验证。对于注册/登录系统,我会recommend using passport

【讨论】:

  • 我尝试使用admin:supersecret,但仍然得到相同的响应...Basic + encoding我在 Stack Overflow 的一些代码中看到了一些代码,在互联网上看到了一些其他示例,并遵循 HTTP Basic Authetication跨度>
  • 你能在标题中添加'Accept': 'application/json'吗?
  • 请删除空中间件,否则您将永远无法通过:app.use(function(err, req, res, next){ console.log(err); //res.status(450).send({err: err.message}) });
  • @rk_Tinelli 已经更新了答案;我认为您误用了该模块。不应该那样使用它。请参阅我的建议。
猜你喜欢
  • 2018-02-23
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
  • 2011-03-06
  • 2020-06-11
  • 2017-02-22
  • 2018-10-08
  • 2018-01-05
相关资源
最近更新 更多