How to make http authentication in REST API call f

2019-02-16 00:45发布

I need to call OpenMRS REST API from Java script to get data from OpenMRS. Below is my java script code:

    function myfunction(){

    var xhr = new XMLHttpRequest();

    xhr.open("GET", "http://localhost:8081/openmrs-standalone/ws/rest/v1/person?q=John", false);
    xhr.setRequestHeader("Authorization: Basic YWRtaW46QWRtaW4xMjM");

    xhr.send("");
    alert(xhr.status);

    }

Where YWRtaW46QWRtaW4xMjM is my base64 coded username:password as explained here. If I do not put the authorization line in the code and check the web app using Firebug, it returns 401 unauthorized status that is expected. But if I put the authorization, nothing is returned and in firebug I do not see any response as well. If I check the URL directly on browser, the page asks for username and password and after giving correct credential, it returns the data normaly. So I am getting some problem of providing the http authentication right from the java script of the app. I have also considered the methods explained here but no luck. Can anyone please help me to authorize the http request right from the javascript?

1条回答
唯我独甜
2楼-- · 2019-02-16 01:01

Here is another similar but different example of how to set the header for authorization purposes, but instead using JQuery and AJAX.

var token = "xyz"
var url = "http://localhost:8081/openmrs-standalone/ws/rest/v1/person?q=John"
$.ajax({
    url: url,
    beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + token)
    },

})
.done(function (data) {
    $.each(data, function (key, value) {
        // Do Something
    })
})
.fail(function (jqXHR, textStatus) {
    alert("Error: " + textStatus);
})

Below is also an example of how you might get an access token using xhr instead of AJAX.

var data = "grant_type=password&username=myusername@website.com&password=MyPassword";

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
    if (this.readyState === 4) {
       console.log(this.responseText);
    }
});

xhr.open("POST", "https://somewebsite.net/token");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("client_id", "4444-4444-44de-4444");

xhr.send(data);

Beware of cross-site domain requests(if you're requesting a token that's not on localhost or within the domain that you are currently working in), as you'll need CORS for that. If you do run into a cross-domain issue, see this tutorial for help, and be sure you have enabled CORS requests from the API as well.

查看更多
登录 后发表回答