How to implement basic HTTP authentication with the VS debug server?

筅森魡賤 提交于 2019-12-01 09:23:12

You could implement your own basic HTTP authentication using ASP.NET. It doesn't seem like a very complicated spec, but see RFC1945 for all the details.

If I had to do it I'd start off with an HttpModule that runs on every request and checks the HTTP header HTTP_AUTHORIZATION. If it's the header for basic authentication, then you can decode username and password. If the header is missing or the username and password are incorrect, then you send back an HTTP 401 response and add the WWW-Authenticate header.

Something like this (not tested, but you get the idea):

public class BasicAuthenticationModule: IHttpModule
{
  public void Init(HttpApplication application)
  {
    application.AuthenticateRequest += new EventHandler(Do_Authentication);
  }

  private void Do_Authentication(object sender, EventArgs e)
  {
    var request = HttpContext.Current.Request;
    string header = request.Headers["HTTP_AUTHORIZATION"];
    if(header != null && header.StartsWith("Basic "))
    {
      // Header is good, let's check username and password
      string username = DecodeFromHeader(header, "username");
      string password = DecodeFromHeader(header, password);

      if(Validate(username, password) 
      {
        // Create a custom IPrincipal object to carry the user's identity
        HttpContext.Current.User = new BasicPrincipal(username);
      }
      else
      {
        Protect();
      }
    }
    else
    {
      Protect();
    }
  }

  private void Protect()
  {
    response.StatusCode = 401;
    response.Headers.Add("WWW-Authenticate", "Basic realm=\"Test\"");
    response.Write("You must authenticate");
    response.End();
  }

  private void DecodeFromHeader()
  {
    // Figure this out based on spec
    // It's basically base 64 decode and split on the :
    throw new NotImplementedException();
  }

  private bool Validate(string username, string password)
  {
    return (username == "foo" && pasword == "bar");
  }

  public void Dispose() {}

  public class BasicPrincipal : IPrincipal
  {
    // Implement simple class to hold the user's identity
  }
}

michielvoo's answer is great, but for sheer simplicity, I went with this in the code for the page:

string authorization = Request.Headers["Authorization"];
string userInfo;
string username = "";
string password = "";
if (authorization != null)
{
     byte[] tempConverted = Convert.FromBase64String(authorization.Replace("Basic ", "").Trim());
     userInfo = System.Text.Encoding.UTF8.GetString(tempConverted);
     string[] usernamePassword = userInfo.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
     username = usernamePassword[0];
     password = usernamePassword[1];
}

if (username == "yourusername" && password == "yourpassword")
{
}
else
{
     Response.AddHeader("WWW-Authenticate", "Basic realm=\"Test\"");
     Response.StatusCode = 401;
     Response.End();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!