WebAPI 返回未经授权或内部服务器错误

问题描述 投票:0回答:1

我正在使用第三方 API,无法获得初始授权来获取会话密钥。我过去曾将此代码与其他几个 API 一起使用过,但很困惑为什么它在这里不起作用。此 API 要求您对用户名和密码进行 Base64 编码以验证您的访问权限。

我尝试了很多方法,但将不同的错误消息缩小到我在编码中使用“Basic”还是“Bearer”。

使用“Bearer”时,错误消息是:

远程服务器返回错误:(401) 未经授权

使用“基本”时,错误消息为:

远程服务器返回错误:(500) 内部服务器错误

鉴于这些消息,我假设“Bearer”是正确的,因为至少它正在尝试并表示访问未经授权......但是,我被告知提供的用户名和密码是正确的!我查了好几遍才确认。

知道是什么原因导致了这个问题吗?

代码:

Sub MyWebApiProcedure()
    Dim vHTTPREQUEST As HttpWebRequest, vHTTPRESPONSE As HttpWebResponse, vSTREAMOBJECT As Stream, vSTREAMREADER As StreamReader, vSESSIONKEY As String

    Dim vURI As String = "https://api.myapi.com/api/myendpoint/"
    Dim vUSERNAME As String = "myusername"
    Dim vPASSWORD As String = "mypassword"
    Dim vTOKEN As String = "Bearer " + System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(vUSERNAME + ":" + vPASSWORD))

    vHTTPREQUEST = CType(WebRequest.Create(vURI), HttpWebRequest)
    vHTTPREQUEST.Method = "GET"
    vHTTPREQUEST.ContentType = "application/x-www-form-urlencoded"
    vHTTPREQUEST.Accept = "application/json"
    vHTTPREQUEST.Headers.Add("Authorization", vTOKEN)

    '>>> THE ERROR OCCURS AT THIS LINE <<<'
    vHTTPRESPONSE = CType(vHTTPREQUEST.GetResponse(), HttpWebResponse)

    vSTREAMOBJECT = vHTTPRESPONSE.GetResponseStream()
    vSTREAMREADER = New StreamReader(vSTREAMOBJECT, Text.Encoding.UTF8)
    vSESSIONKEY = vSTREAMREADER.ReadToEnd()

    vHTTPRESPONSE.Close()
    vSTREAMREADER.Close()

    Response.Write(vSESSIONKEY)
End Sub

编辑: 根据文档从支持团队收到了Python版本。

encoded_auth_text = base64.b64encode(b'username' + b':' + b'password')

response = requests.post(url='https://api.myapi.com/api/myendpoint', headers={'Authorization': encoded_auth_text}, timeout=30)
asp.net rest webapi internal-server-error
1个回答
0
投票

答案是使用 POST 请求而不是 GET 请求。而且,因为它是用户名和密码的 Base64 编码。您需要使用“基本”身份验证。

学到的教训是更批判性地阅读文档。

Sub MyWebApiProcedure()
    Dim vHTTPREQUEST As HttpWebRequest, vHTTPRESPONSE As HttpWebResponse, vSTREAMOBJECT As Stream, vSTREAMREADER As StreamReader, vSESSIONKEY As String

    Dim vURI As String = "https://api.myapi.com/api/myendpoint/"
    Dim vUSERNAME As String = "myusername"
    Dim vPASSWORD As String = "mypassword"
    Dim vTOKEN As String = "Basic " + System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(vUSERNAME + ":" + vPASSWORD))

    vHTTPREQUEST = CType(WebRequest.Create(vURI), HttpWebRequest)
    vHTTPREQUEST.Method = "POST"
    vHTTPREQUEST.ContentType = "application/x-www-form-urlencoded"
    vHTTPREQUEST.Accept = "application/json"
    vHTTPREQUEST.Headers.Add("Authorization", vTOKEN)

    vHTTPRESPONSE = CType(vHTTPREQUEST.GetResponse(), HttpWebResponse)

    vSTREAMOBJECT = vHTTPRESPONSE.GetResponseStream()
    vSTREAMREADER = New StreamReader(vSTREAMOBJECT, Text.Encoding.UTF8)
    vSESSIONKEY = vSTREAMREADER.ReadToEnd()

    vHTTPRESPONSE.Close()
    vSTREAMREADER.Close()

    Response.Write(vSESSIONKEY)
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.