Isaac
asked on
API connection with username and password
Hello,
I am trying to access an endpoint with API using Basic authentication (Username and password). I tried two methods that did not work for me.
Method 1:
I get this in IE
Method 2:
I get the same error in IE. Base64 is undefined.
Any help would be much appreciated.
Thanks!
I am trying to access an endpoint with API using Basic authentication (Username and password). I tried two methods that did not work for me.
Method 1:
var apiTest = new XMLHttpRequest();
var username ='testUser';
var password ='letUserIn1#';
apiTest.open('GET', 'https://internal.com/agency');
apiTest.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
apiTest.setRequestHeader('Accept', 'application/json');
apiTest.onload = function() {
var apiData = JSON.parse(apiTest.responseText);
console.log(apiData[0]);
};
apiTest.send();
I get the following error for method 1 in Chrome:I get this in IE
Method 2:
$.ajax({
url: 'https://internal.com/agency',
method: 'GET',
crossDomain: true,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( 'testUser:letUserIn1#') );
},
success: function( data, txtStatus, xhr ) {
console.log( data );
console.log( xhr.status );
}
});
Here's the error I get:I get the same error in IE. Base64 is undefined.
Any help would be much appreciated.
Thanks!
for user authentication, you may try:
use it like:
public static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
}
use it like:
HttpWebRequest request = null;
request = WebRequest.Create("http://yourSite/path/someService.svc/rest/test") as HttpWebRequest;
SetBasicAuthHeader(request, "userName", "userPassword");
ASKER
This looks like something you would do in node. Would it work in just a regular javaScript file? I'm using it from within SharePoint 2013.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
That worked when I added the contentType header of "application/json". Thanks!
try to change it to POST and see if your RESTful web service can accept it?
apiTest.open('POST', 'https://internal.com/agency');