C# HttpListener:如何获取http用户和密码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1147308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:22:04  来源:igfitidea点击:

HttpListener: how to get http user and password?

c#passwordshttplistener

提问by FWH

I'm facing a problem here, with HttpListener.

我在这里遇到了 HttpListener 的问题。

When a request of the form

当表单的请求

http://user:password@example.com/

is made, how can I get the user and password ? HttpWebRequest has a Credentials property, but HttpListenerRequest doesn't have it, and I didn't find the username in any property of it.

制作完成后,如何获取用户名和密码?HttpWebRequest 有一个 Credentials 属性,但 HttpListenerRequest 没有,我在它的任何属性中都没有找到用户名。

Thanks for the help.

谢谢您的帮助。

采纳答案by Matt Brindley

What you're attempting to do is pass credentials via HTTP basic auth, I'm not sure if the username:password syntax is supported in HttpListener, but if it is, you'll need to specify that you accept basic auth first.

您尝试做的是通过 HTTP 基本身份验证传递凭据,我不确定 HttpListener 中是否支持 username:password 语法,但如果是,您需要先指定接受基本身份验证。

HttpListener listener = new HttpListener();
listener.Prefixes.Add(uriPrefix);
listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
listener.Start();

Once you receive a request, you can then extract the username and password with:

收到请求后,您可以使用以下命令提取用户名和密码:

HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity;
Console.WriteLine(identity.Name);
Console.WriteLine(identity.Password);

Here's a full explanationof all supported authenitcation methods that can be used with HttpListener.

是可与 HttpListener 一起使用的所有受支持的身份验证方法的完整说明

回答by anonymous coward

Get the Authorizationheader. It's format is as follows

获取Authorization标题。它的格式如下

Authorization: <Type> <Base64-encoded-Username/Password-Pair>

Example:

例子:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

The username and password is colon-seperated (in this example, Aladdin:open sesame), then B64-encoded.

用户名和密码以冒号分隔(在本例中为Aladdin:open sesame),然后是 B64 编码。

回答by Darin Dimitrov

You need to first enable Basic Authentication:

您需要先启用基本身份验证:

listener.AuthenticationSchemes = AuthenticationSchemes.Basic;

Then in your ProcessRequest method you could get username and password:

然后在您的 ProcessRequest 方法中,您可以获得用户名和密码:

if (context.User.Identity.IsAuthenticated)
{
    var identity = (HttpListenerBasicIdentity)context.User.Identity;
    Console.WriteLine(identity.Name);
    Console.WriteLine(identity.Password);
}