WWW-Authenticate (Basic) in ASP.NET

Mit nur wenigen Zeilen lässt sich die Basic Authentication (http://de.wikipedia.org/wiki/HTTP-Authentifizierung) in C# umsetzen:

const String KEY = "BasicAuthKey";
const String Basic = "Basic ";

if (Session.Contents[KEY] == null)
{
    Response.BufferOutput = true;

    String auth = Request.Headers["Authorization"] ?? String.Empty;
    auth = System.Text.Encoding.UTF8.GetString(
        Convert.FromBase64String(auth.StartsWith(Basic)
        ? auth.Substring(Basic.Length) : String.Empty));
    if (auth == "username:password")
    {
        Session.Contents.Add(KEY, new Object());
    }
    else
    {
        Response.Clear();
        Response.Headers.Set(
            "WWW-Authenticate",
            "Basic realm=\"RegisteredUsers@domain.tld\"");
        Response.SetStatus(HttpStatusCode.Unauthorized);
        Response.End();
    }
}

Schreib' einen Kommentar