AJAX POST请求隐藏基本认证证书 [英] AJAX POST Request Hide Basic Auth Credentials

查看:517
本文介绍了AJAX POST请求隐藏基本认证证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究如何AJAX POST请求发送到我的API,我想了解如何正确地传递基本身份验证凭据。

 接口API
 

https://www.example.com/app/ ------- > https://api.example.com/

使用这个例子中,我发现计算器 - ?couldn't人查看JS的来源,看到我的用户名和密码以明文形式,并有机会获得我所有的API函数

如果是这样,我怎么把我的用户名和密码,而不显示给世界呢?

  $。阿贾克斯({
    网址:yoururl,
    用户名:用​​户名,
    密码:密码,
    键入:POST,
    的contentType:应用程序/ x-WWW的形式urlen codeD',
    数据类型:文本,
    xhrFields:
    {
        withCredentials:真
    },
    beforeSend:功能(XHR){
        xhr.setRequestHeader('授权','基本'+ BTOA(用户名+:+密码));
    }
});
 

解决方案

是的,如果你硬code你的用户名和密码,在JavaScript中,整个世界都将能够看到和使用它们。

您不应使用基本身份验证来保护网络的API。还有,我描述这个答案的几种选择。我的preference与 OAuth2 。从JavaScript客户端使用它,你想看看隐含的流动,这是专门为不可信的客户端。

I've been researching ways to send AJAX POST requests to my API and I'm trying to understand how to pass basic auth credentials correctly.

          Interface                    API

https://www.example.com/app/ -------> https://api.example.com/

Using this example I found on StackOverflow--couldn't anyone view the source of the JS, see my username and password in cleartext, and have access to all my API functions?

If so, how do I pass my username and password without showing it to the world?

$.ajax({  
    url: 'yoururl',
    username : username,
    password :password,
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    dataType: "text",
    xhrFields: 
    {
        withCredentials: true
    },
    beforeSend: function (xhr) { 
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));             
    }
});

解决方案

Yes, if you hardcode your username and password in your JavaScript, the whole world will be able to see them and use them.

You should not use basic authentication to protect web APIs. There are several alternatives as I describe in this answer. My preference is with OAuth2. Using it from a JavaScript client, you want to look at the implicit flow, which is specifically for untrusted clients.

这篇关于AJAX POST请求隐藏基本认证证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆