Dan Lugg
Dan Lugg

Reputation: 20621

HTTP Basic Authorization in .NET

Perhaps I'm missing something, or perhaps .NET is missing something (preferably the former)

When building an application (not exclusively ASP.NET, but such is my situation; specifically an ASP.NET hosted WCF DS) it seems there's no native way to create a NetworkCredential object from an HttpRequest, or any similar request/header container,.

Do we always have to roll our own, or is there some magic tucked away in System.Net.* or System.Web.* with a signature like:

NetworkCredential GetAuthorization(HttpRequest request);

It's trivial I know, but I would assume something standard to the HTTP architecture would be included in something that is otherwise so encompassing (.NET)

So, home-brew string manipulation, or magic method hiding somewhere?

Upvotes: 1

Views: 571

Answers (1)

Richard Deeming
Richard Deeming

Reputation: 31248

I don't think there's anything built-in; it would be of limited use, since most clients use Kerberos or Digest authentication instead.

However, it's fairly simple to roll your own:

static NetworkCredential ParseBasicAuthorizationHeader(string value)
{
   if (string.IsNullOrWhiteSpace(value)) 
   {
      return null;
   }
   if (!value.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase)) 
   {
      return null;
   }

   byte[] data = Convert.FromBase64String(value.Substring(6));
   value = Encoding.GetEncoding("ISO-8859-1").GetString(data);

   int index = value.IndexOf(':');
   if (index == -1 || index == 0 || index == value.Length - 1) 
   {
      return null;
   }

   return new NetworkCredential(
      value.Substring(0, index),    // Username
      value.Substring(index + 1));  // Password
}

Bear in mind that, like all other HTTP headers, the Authorization header is completely controlled by the client, and should therefore be treated as untrusted user input.

Upvotes: 1

Related Questions