12

I'm facing a problem here, with 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.

Thanks for the help.

jdphenix
  • 15,022
  • 3
  • 41
  • 74
FWH
  • 3,205
  • 1
  • 22
  • 17

3 Answers3

30

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.

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 explanation of all supported authenitcation methods that can be used with HttpListener.

csharpfolk
  • 4,124
  • 25
  • 31
Matt Brindley
  • 9,739
  • 7
  • 47
  • 51
  • Sorry, I said "I'm not if the username:password syntax is supported in HttpListener", but of course it's the client that will convert this into a "WWW-Authenticate: basic" header, so it only matters if the client supports it. I believe support for it has been dropped from IE recently. – Matt Brindley Jul 18 '09 at 11:44
5

Get the Authorization header. It's format is as follows

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.

5

You need to first enable Basic Authentication:

listener.AuthenticationSchemes = AuthenticationSchemes.Basic;

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

if (context.User.Identity.IsAuthenticated)
{
    var identity = (HttpListenerBasicIdentity)context.User.Identity;
    Console.WriteLine(identity.Name);
    Console.WriteLine(identity.Password);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928