VBA XMLHTTP clear authentication?

不问归期 提交于 2019-12-29 06:30:14

问题


I am writing a set of VBA macros in which it uses the XMLHTTP object to send asynchronous requests to a server. I am sending Basic Authentication with:

XMLHttpReq.setRequestHeader "Authorization","Basic " & Base64EncodedUserPass

This works great the first time. But if the user changes their userid/password, even if the code creates a brand new XMLHttpReq object and sets this header to the new information, it logs in to the server as the first user, presumably from cached credentials.

How can I cause the code to "forget" that I have logged in before, and re-authorize?

Edit as requested, the relevant part of the code; it really isn't very complicated:

myURL = "http://my.domain.com/myscript.cgi"
Dim oHttp As New MSXML2.XMLHTTP
oHttp.Open "POST", myURL, False
oHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded'"
oHttp.setRequestHeader "Authorization","Basic " & Base64EncodedUsernamePassword
oHttp.send "PostArg1=PostArg1Value"
Result = oHttp.responseText

回答1:


These questions have been discussed in many ways due to major browsers different implementations of caching methods.

I will give you what worked for me and then the sources I found on this feature.

The only solution I could came across was to force the browser to not cache the request.

myURL = "http://my.domain.com/myscript.cgi"
Dim oHttp As New MSXML2.XMLHTTP
oHttp.Open "POST", myURL, False
oHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded'"
oHttp.setRequestHeader("Cache-Control", "no-cache");
oHttp.setRequestHeader("Pragma", "no-cache");
oHttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
oHttp.setRequestHeader "Authorization","Basic " & Base64EncodedUsernamePassword
oHttp.send "PostArg1=PostArg1Value"
Result = oHttp.responseText

It seems that Cache-Control works on most browsers and Pragma only on Firefox and not IE (don't know why...)

If-Modified-Since is used for IE, since IE uses different settings in his own algorithm to determine whether or not the request should be cached. XMLHttpRequest seem to not be treated as the same as HTTP responses.

Careful : With this code you will need username and password each time a new object is created. Maybe you should create a new object, instantiate it once and then destroy it after use. In between you would have all your requests handled in different functions with only one authentication.


Sources

MSDN setRequestHeader Method

MSDN IXMLHTTPRequest

XMLHTTPREQUEST CACHING TESTS

XMLHttpRequest and Caching



来源:https://stackoverflow.com/questions/11526810/vba-xmlhttp-clear-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!