如何基本身份验证与HttpListener工作打交道时?
-
05-09-2019 - |
题
这似乎是一个基本的问题,并返回到Http协议101.但我了解基本认证是如何工作遇到了困难。我实现一个窗口服务,需要的是安全的。我想获得用户名和密码,验证用户自定义的用户存储。我也希望尽量减少登录的呼叫号码,登录电话表示对我们的SQL服务器的呼叫。什么到目前为止,我已经开始是这样的:
在我看来UserAuthorized函数必须让我的自定义登录调用的方式。但是,我不希望有这样做,每一次。是否基本认证维持,如果你登录了,还是有一个缓存线程安全的解决方案,我应该探索。
噢我也想使它所以,当用户是认证和对象被创建和维持在所述螺纹为听者指在后续的回调为用户/连接。但由于ListenerCallback是静态的我不知道这是如何实现的。
预先感谢任何帮助,我真正体会它和StackOverflow上。
public void ThreadProc() {
string uriPrefix = ConfigurationManager.AppSettings["ListenerPrefix"];
HttpListener listener = new HttpListener();
listener.Prefixes.Add(uriPrefix);
listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
listener.Start();
Console.WriteLine("Start listening on " + uriPrefix);
Console.WriteLine("Press Control-C to stop listener...");
while (listening) {
IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
result.AsyncWaitHandle.WaitOne();
}
}
public static void ListenerCallback(IAsyncResult result) {
HttpListener listener = (HttpListener)result.AsyncState;
HttpListenerContext context = listener.EndGetContext(result);
WebDavEngine engine = new WebDavEngine(context.User);
context.Response.SendChunked = false;
FileLogger.Level = LogLevel.Debug;
engine.IgnoreExceptions = false;
if (UserAutorized(context)) {
try {
engine.Run(context, listener.Prefixes);
engine.CommitTransaction();
} catch {
engine.RollBackTransaction();
} finally {
engine.CloseConnection();
}
} else
context.Response.StatusCode = 401;
if (context.Response.StatusCode == 401)
ShowLoginDialog(context, context.Response);
try {
context.Response.Close();
} catch {
// client closed connection before the content was sent
}
}
private static bool UserAutorized(HttpListenerContext context) {
HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity;
if (!identity.IsAuthenticated) {
string username = identity.Name;
// workaround for Windows Vista Basic authentication. User name may be submitted in the following format: Machine\User.
int ind = username.LastIndexOf('\\');
if (ind > 0)
username = username.Remove(0, ind + 1);
Console.WriteLine("Trying Authentication since identity is NOT authenticated");
return false;
} else {
Console.WriteLine("identity.IsAuthenticated: " + identity.IsAuthenticated.ToString());
return identity.IsAuthenticated;
}
}
编辑: +1单独的文件,真正睁开眼睛的身份验证方案的美服以及它们如何工作。除非我一个准备好这个错误,它似乎是一个摘要的方案是能够保持一个“会话”,或者至少一个到期重试我的自定义验证。
解决方案 2
感谢您的规范,我理解它。我还是设法解决我的问题,它不符合规范相关,而是一个设计/托管问题。
其他提示
HTTP基本需要与每个请求的登录凭证。 HTTP没有会话的任何概念,所以你真的不能告诉如果有人“已经登录”。
不隶属于 StackOverflow