Dead simple ASP.NET MVC 5 password protection?
I have an ASP.NET MVC 5 web application running on Azure as a webrole.
Is there a way to easily password protect an entire site? I don't need a registration or account, just one password to login to the site (and possibly a username, but that is not required). Something similar to a .htaccess file.
Every ASP.NET MVC authentication example I look at comes with a huge amount of code to implement, and Azure doesn't seem to be able to support basic authentication (at least not that easy).
source to share
You are correct, there is no basic authentication support in ASP.NET MVC. However, you can easily add it 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 with attributes:
[BasicAuthenticationAttribute("your-username", "your-password", BasicRealm = "your-realm")]
public class HomeController : BaseController
{
...
}
To protect your entire site, add this filter to global filters:
protected void Application_Start()
{
...
GlobalFilters.Filters.Add(new BasicAuthenticationAttribute("your-username", "your-password"));
...
}
source to share