.net - HttpListener 认证
问题描述
我目前正在使用 .NET 中的代理,该代理必须具有使用基本身份验证的选项。我已经广泛地寻找示例,但似乎无法让它发挥作用。
我正在基于布尔值设置 AuthenticationSchemes,然后我正在设置“WWW-Authenticate”标头以及“Authorization”标头。不幸的是,我总是收到 401 响应。代理应该接受 admin/admin 作为用户名和密码,它不必非常安全。
这是我当前的代码:
public void StartProxy() {
string urlBase = $"http://127.0.0.1:{port}/";
if (isStarted) {
return;
}
if(httpListener == null) {
httpListener = new HttpListener();
}
httpListener.Prefixes.Add(urlBase);
if (basicAccessAuth) {
httpListener.AuthenticationSchemes = AuthenticationSchemes.Basic;
}
isStarted = true;
httpListener.Start();
IAsyncResult result = httpListener.BeginGetContext(new AsyncCallback(WebRequestCallback), httpListener);
}
private void WebRequestCallback(IAsyncResult result) {
if (httpListener == null) {
return;
}
HttpListenerContext context = httpListener.EndGetContext(result);
httpListener.BeginGetContext(new AsyncCallback(WebRequestCallback), httpListener);
if (ReceiveWebRequest != null) {
ReceiveWebRequest(context);
}
ProcessRequest(context);
}
private void ProcessRequest(HttpListenerContext Context) {
HttpListenerRequest Request = Context.Request;
HttpListenerResponse Response = Context.Response;
NameValueCollection nvCol = new NameValueCollection();
nvCol.Add("Authorization", "admin:admin");
if (basicAccessAuth) {
Request.Headers.Add(nvCol);
Response.Headers.Add("WWW-Authenticate");
HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)Context.User.Identity;
MessageBox.Show(identity.Name);
}
StringBuilder sb = new StringBuilder();
if (Request.UrlReferrer != null) {
sb.AppendLine("Referer: " + Request.UrlReferrer);
}
if (Request.UserAgent != null) {
sb.AppendLine("User-Agent: " + Request.UserAgent);
}
for (int i = 0; i < Request.Headers.Count; i++) {
sb.AppendLine(Request.Headers.Keys[i] + ":" + " " + Request.Headers[i]);
}
sb.AppendLine();
//will this fail if headers are added/removed ?
string Output = getHtmlForRequest(Request.Headers[5]);
sb.AppendLine(Output);
Task.Run(() => {
LogModel log = new LogModel(sb.ToString());
addMessageToLogDelegate(log);
});
byte[] bOutput = System.Text.Encoding.UTF8.GetBytes(Output);
Response.ContentType = "text/html";
Response.ContentLength64 = bOutput.Length;
Stream OutputStream = Response.OutputStream;
OutputStream.Write(bOutput, 0, bOutput.Length);
OutputStream.Close();
}
如您所见,我在“ProcessRequest”函数中设置了标题,但似乎无法使其正常工作。我做错了什么,我该如何解决?
解决方案
推荐阅读
- ansible - 错误!未能组合变量,预期的字典,但得到了一个“字典”和一个“AnsibleUnicode”
- vtiger - Vtiger 错误:找不到类“Vtiger_Package”
- ios - xcode 13 上的导入框架问题:无法构建 Objective-C 模块“DataStorage”
- microservices - Zuul 和 Ribbion 的区别
- azure - 在 Azure 数据工厂中将日期减去 currentDate()
- typescript - 导入 TypeScript 失败
- reactjs - 如何调整 React Table 中的列大小
- javascript - 在文件(txt 或任何)上写入 SQL QUERY 内容
- xamarin - 从 viewmodelpage 使标签在 loginpage 中可见
- ejabberd - Ejabberd 的 CDR(呼叫数据记录)