问题
I am following authentication method described at http://blogs.msdn.com/b/astoriateam/archive/2010/07/21/odata-and-authentication-part-6-custom-basic-authentication.aspx
I am able to consume service using ASP.NET (not a problem at all). Now I would like to create a plain HTML page and access the service using "OData Javascript Library" (datajs).
If I disable authentication and request for data, it works fine. I could not find any sample code on how to send authentication header information using "datajs" (when used with OData.Request and/or OData.Read).
Can anyone help me on this?
回答1:
If you're using basic authentication as described in the post, you can use the request parameter of OData.request to pass in the username and password.
http://datajs.codeplex.com/wikipage?title=datajs%20OData%20API#OData.request
You could write something like:
OData.request({requestUri:"...", user:"user", password:"secret"}, function (data) { ... });
Note that this will not work with cross-domain AJAX.
Hope this helps!
回答2:
If you are using datajs library for service integration then you can either use above method to odata service or you can use below method as shown in example. Here I have setted headers in variable 'oHeader' and passing it using 'btoa' function which encodes credentials.
var oHeaders = {};
var uName="abc";
var pass="123";
var requrl="{service path}";
oHeaders['Authorization'] = "Basic " + btoa(uName +':'+ pass);
var request = {
headers: oHeaders,
requestUri: requrl,
method: "GET",
};
OData.request(request, function(data) {
// success block
}, function(data) {
// error block
});
来源:https://stackoverflow.com/questions/7088021/how-to-pass-authentication-header-to-odata-service