Link to home
Start Free TrialLog in
Avatar of Isaac
IsaacFlag for United States of America

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:

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

Open in new window

I get the following error for method 1 in Chrome:
User generated imageI get this in IE
User generated image
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 );
    }
});

Open in new window

Here's the error I get:
User generated imageI get the same error in IE.  Base64 is undefined.

Any help would be much appreciated.

Thanks!
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

not too sure if GET is working fine with authentication.

try to change it to POST and see if your RESTful web service can accept it?

apiTest.open('POST', 'https://internal.com/agency');
for user authentication, you may try:

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

Open in new window


use it like:
HttpWebRequest request = null;
request = WebRequest.Create("http://yourSite/path/someService.svc/rest/test") as HttpWebRequest;
SetBasicAuthHeader(request, "userName", "userPassword");

Open in new window

Avatar of Isaac

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
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Isaac

ASKER

That worked when I added the contentType header of "application/json".  Thanks!