超级简单的ASP.NET MVC 5密码保护?

6
我有一个在Azure上作为Web角色运行的ASP.NET MVC 5 Web应用程序。
是否有一种简单的方法来对整个网站进行密码保护?我不想要任何注册或帐户处理,只需要一个单一的密码来进入网站(也许还需要用户名,但这不是必需的)。类似于.htaccess文件的东西。
我看到的每个关于ASP.NET MVC身份验证的示例都有大量的实现代码,Azure似乎也不能轻松支持基本身份验证。

我只会生成模板并删除注册和账户相关的内容,然后将一个用户添加到表中。 - jamesSampica
1个回答

13

您说得对,ASP.NET MVC默认不支持基本身份验证。但是,您可以使用操作过滤器轻松添加它,如这里所述。首先,您需要创建一个操作过滤器:

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();
        }
    }

你可以使用属性来保护操作和控制器:

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

为了保护整个网站,请将此过滤器添加到全局过滤器中:

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

这是一个非常好的答案,而且运行得非常好。干净、简单、快速实现! - juFo
这很棒 - 我该如何添加一个注销按钮? - niico
当我将其用作全局过滤器时,OnActionExecuting会一遍又一遍地被调用...有什么建议吗? - Captain_Planet
1
这个解决方案可能存在这里描述的缺陷:https://dev59.com/dGIj5IYBdhLWcg3wilrB#35330494 - James

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接