Dead simple ASP.NET MVC 5 password protection?

守給你的承諾、 提交于 2019-12-05 16:20:22
ranquild

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