gpt4 book ai didi

过早发送 C# HTTP 基本身份验证凭据

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:38 25 4
gpt4 key购买 nike

我正在尝试登录到使用 HTTP 基本身份验证的服务器 (REST API)。请求看起来像这样:

public JObject PerformLogin(string username, string password)
{
string html = string.Empty;

this.username = username;
this.password = password;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(auth_url_internal);
request.AllowAutoRedirect = true;
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Method = "GET";
request.CookieContainer = cookies;
request.KeepAlive = true;
//request.ServicePoint.Expect100Continue = false;
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
request.Headers.Add("Accept-Language", "de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4");
request.PreAuthenticate = true;
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;

string authInfo = username + ":" + password;
authInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(authInfo));
request.Headers.Add("Authorization", "Basic " + authInfo);

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}

JObject jresponse = JObject.Parse(html);

sess_url_internal = jresponse["internalUrl"].ToString();
sess_url_public = jresponse["publicUrl"].ToString();

return jresponse;
}

这基本上是有效的,但是凭证发送得太早了。

首先,我使用 curl 详细查看了流量情况,发现了一个“Location:”-Header,这意味着发生了重定向。详细地说,服务器将我从 /api/rest/authenticate?version=1.0 重定向到 /authenticationbasic/login?AlcApplicationUrl=/api/rest/authenticate%3fversion=1.0 (URL2).

但是,Chrome 将凭据发送到 URL2,我的程序将它们发送到 URL1,这太早了,因为服务器期望它们在 URL2,而我的应用程序不发送任何凭据,因此得到错误的返回。

我怎样才能改变这种行为?

最佳答案

所以在 x... 的帮助下我想出了怎么做:

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 之后简单地添加

if ((int)response.StatusCode == 302) // redirect
{
/*
Call the function recursively with the new URL, found in
response.Headers["Location"], in my case this would be:
*/

auth_url_internal = response.Headers["Location"];
return PerformLogin(username, password);
}

关于过早发送 C# HTTP 基本身份验证凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38822860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com