Dead simple ASP.NET MVC 5 password protection?

2019-05-03 18:24发布

问题:

I have an ASP.NET MVC 5 web application running on Azure as a webrole.

Is there any way to easily password protect the entire website? I do not want any signup or account handling, just a single password to enter the site (and perhaps a username, but that's not required). Something similar to a .htaccess file.

Every example on authentication for ASP.NET MVC I'm looking at comes with an enormous amount of code to implement, and Azure does not seem to be able to support Basic Authentication (at least not easily).

回答1:

You are right, there is no support for Basic Authentication in ASP.NET MVC out of the box. However, you can easily add it by using action filters, as described here. First you need to create an action filter:

public class BasicAuthenticationAttribute : ActionFilterAttribute
    {
        public string BasicRealm { get; set; }
        protected string Username { get; set; }
        protected string Password { get; set; }

        public BasicAuthenticationAttribute(string username, string password)
        {
            this.Username = username;
            this.Password = password;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var req = filterContext.HttpContext.Request;
            var auth = req.Headers["Authorization"];
            if (!String.IsNullOrEmpty(auth))
            {
                var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':');
                var user = new { Name = cred[0], Pass = cred[1] };
                if (user.Name == Username && user.Pass == Password) return;
            }
            var res = filterContext.HttpContext.Response;
            res.StatusCode = 401;
            res.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Ryadel"));
            res.End();
        }
    }

Then you can protect actions, controllers by using attributes:

[BasicAuthenticationAttribute("your-username", "your-password", BasicRealm = "your-realm")]
public class HomeController : BaseController
{
   ...
}

To protect the entire website, add this filter to global filters:

protected void Application_Start()
{
    ...
    GlobalFilters.Filters.Add(new BasicAuthenticationAttribute("your-username", "your-password"));
    ...
}