对REST API进行安全调用

时间:2019-05-18 11:20:28

标签: javascript reactjs axios basic-authentication

我是React JS的新手。使用ReactJS,我可以安全地调用REST API。我知道我需要在调用的标头中提供令牌/某种凭证,但是我不知道如何确切地执行此操作以最终写入请求的标头。

我已经创建了应用程序,导入了所需的库,然后运行了该应用程序。当我运行该应用程序并单击将触发testBPMAPI()函数的按钮时,我在浏览器控制台中收到“ 401未经授权”错误。我正在Chrome和Firefox上进行测试。

我已经测试过“邮递员”应用程序,在该应用程序中,我需要提供用户名和密码(API需要基本身份验证)并且可以正常工作。但是,我不知道如何构造标题以传递凭据。

testCallBPMAPI() {

  axios.get('http://localhost:7004/bpm/services/rest/tasks').then(resp => {
    console.log('from testCallBPMAPI():',resp.data);
  });
}

我希望得到API结果,在上面的例子中是包含更多对象的数组。

我将服务电话更新为以下内容:

testCallBPMAPI()
    {
        var session_url = 'http://localhost:7004/bpm/services/rest/tasks';
        var username = 'user1';
        var password = 'pass1';
        var basicAuth = 'Basic ' + btoa(username + ':' + password);
        console.log('basicAuth',basicAuth)
        axios.post(session_url, {}, {
          headers: { 'Authorization': + basicAuth }

        }).then(function(response) {
          console.log('Authenticated');
        }).catch(function(error) {
          console.log('Error on Authentication');
        });
    }

还是同样的错误,401未经授权

我更新了代码以包含“ auth”对象:

testCallBPMAPI()
    {
        var session_url = 'http://localhost:7004/bpm/services/rest/tasks';
        var username = 'user1';
        var password = 'pass1';
        var basicAuth = 'Basic ' + btoa(username + ':' + password);

        axios.post(session_url, {}, {
          headers: { 'Authorization': + basicAuth,
                     'mode': 'cors' },


          auth: {
            username: 'user1',
            password: 'pass1'
          },


        }).then(function(response) {
          console.log('Authenticated');
        }).catch(function(error) {
          console.log('Error on Authentication');
        });


    }

现在我不再收到“ 401未经授权”错误。

相反,我收到服务器错误500:

browser console log

如何进一步解决该问题?

谢谢。

0 个答案:

没有答案