经典 asp 使用 addheader 调用 api 进行授权

classic asp calling an api using addheader for authorization

我有一个调用 api 的页面,该页面在测试模式下不需要任何授权。
我们现在正在转移到需要用户名和密码的实时环境。

api 提供商发送了以下消息:

To access these services please send the requests by adding following HTTP header. Authorization: Basic Base64Encode(“username: password”)

我不确定语法是否正确,想知道是否有人可以帮助我。

原始调用(并且工作完美)是:

Dim xmlobj, username, password
username="myusername"
password="mypassword"
Set xmlobj = server.CreateObject("MSXML2.DOMDocument.3.0")
xmlobj.async = false
xmlobj.setProperty "ServerHTTPRequest", True
xmlObj.AddHeader "Authorization", "Basic", Base64Encode(username & ":" & password)
xmlobj.load(sUrl)

以上代码抛出错误

/api-test.asp|20|800a000d|Type_mismatch:_'Base64Encode'

如有任何帮助,我们将不胜感激。

正如我在 comments 中提到的,Authorization header 的语法不正确。

API 示例不期望 "Base64Encode('username','password')" 这是 API 提供的示例,向您展示如何获取字符串 "username:password" 并对其进行 Base64 编码这正是 Authorization header 所期待的。

但是您仍然需要 Base64Encode() 函数定义才能使代码正常工作。

Base64Encode() and MyASC() functions are taken from Base64 encode VBS function (vb encoder algorithm), source code

像这样的东西应该有用;

<%
Function Base64Encode(inData)
  'rfc1521
  '2001 Antonin Foller, Motobit Software, http://Motobit.cz
  Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  Dim cOut, sOut, I

  'For each group of 3 bytes
  For I = 1 To Len(inData) Step 3
    Dim nGroup, pOut, sGroup

    'Create one long from this 3 bytes.
    nGroup = &H10000 * Asc(Mid(inData, I, 1)) + _
      &H100 * MyASC(Mid(inData, I + 1, 1)) + MyASC(Mid(inData, I + 2, 1))

    'Oct splits the long To 8 groups with 3 bits
    nGroup = Oct(nGroup)

    'Add leading zeros
    nGroup = String(8 - Len(nGroup), "0") & nGroup

    'Convert To base64
    pOut = Mid(Base64, CLng("&o" & Mid(nGroup, 1, 2)) + 1, 1) + _
      Mid(Base64, CLng("&o" & Mid(nGroup, 3, 2)) + 1, 1) + _
      Mid(Base64, CLng("&o" & Mid(nGroup, 5, 2)) + 1, 1) + _
      Mid(Base64, CLng("&o" & Mid(nGroup, 7, 2)) + 1, 1)

    'Add the part To OutPut string
    sOut = sOut + pOut

    'Add a new line For Each 76 chars In dest (76*3/4 = 57)
    'If (I + 2) Mod 57 = 0 Then sOut = sOut + vbCrLf
  Next
  Select Case Len(inData) Mod 3
    Case 1: '8 bit final
      sOut = Left(sOut, Len(sOut) - 2) + "=="
    Case 2: '16 bit final
      sOut = Left(sOut, Len(sOut) - 1) + "="
  End Select
  Base64Encode = sOut
End Function

Function MyASC(OneChar)
  If OneChar = "" Then MyASC = 0 Else MyASC = Asc(OneChar)
End Function

Dim xmlobj, username, password
username="myusername"
password="mypassword"
Set xmlobj = server.CreateObject("MSXML2.XMLHTTP.3.0")
xmlobj.Open "GET", sUrl, False
xmlobj.setRequestHeader "Authorization", "Basic " & Base64Encode(username & ":" & password)
xmlobj.Send

Dim xmldoc
If xmlobj.status = 200 Then
  Set xmldoc = Server.CreateObject("MSXML2.DOMDocument.3.0")
  xmldoc.Load xmlobj.ResponseXML
Else
  Response.Write "An error occurred!"
End If
%>