I had some questions about authentication from users of the Excel Rest library. Typically Rest queries are authorized through the use of a developer key issued to registered users, but some sites need authorization as well.
HTTP basic authorization is accomplished by encoding a username and password into the headers of a request, and although there is plenty of information out there about how to do this with jQuery and javaScript and other languages, tracking down the solution from VBA was a little more difficult.
The solution is as below, with acknowledgement to http://pastie.org/1192157
Public Function httpGET(fn As String, _ Optional authUser As String = vbNullString, _ Optional authPass As String = vbNullString) As String pHtml = fn Dim oHttp As Object Set oHttp = CreateObject("Microsoft.XMLHTTP") Call oHttp.Open("GET", pHtml, False) If (authUser <> vbNullString) Then ' need to do basic authentication ' acknowledgement to http://pastie.org/1192157 oHttp.SetRequestHeader "Content-Type", "application/json" oHttp.SetRequestHeader "Accept", "application/json" oHttp.SetRequestHeader "Authorization", "Basic " + _ Base64Encode(authUser + ":" + authPass) End If Call oHttp.Send("") httpGET = oHttp.ResponseText Set oHttp = Nothing End Function
Public Sub testneedsPass() Dim cr As cRest Set cr = restQuery("needsPass", "needsPass", _ , , , , , True, , , True, , "someuser", "somepassword") End Sub