AJAX POST Request Hide Basic Auth Credentials

*爱你&永不变心* 提交于 2019-12-14 02:05:52

问题


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));             
    }
});

回答1:


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.



来源:https://stackoverflow.com/questions/31747511/ajax-post-request-hide-basic-auth-credentials

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!