Dead simple ASP.NET MVC 5 password protection?

穿精又带淫゛_ 提交于 2019-12-07 08:55:09

问题


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"));
    ...
}


来源:https://stackoverflow.com/questions/29971693/dead-simple-asp-net-mvc-5-password-protection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!