java rest接口 验证,如何在javascript的REST API调用中进行http身份验证

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值