首页 > 解决方案 > 如何使用 IIS 对 MVC 路由进行密码保护

问题描述

我想密码保护我的 MVC 5 应用程序的路线之一。我不想经历 Forms Auth 或 [Authorize] 属性等过程。我只想像往常一样部署应用程序并使用 IIS 来保护其中一个路由。

egmydomain.com/ 对世界开放

mydomain.com/Folder1 密码保护

使用 IIS pwd 保护物理文件夹既快速又简单,但是如果我创建一个虚拟目录或应用程序来匹配该 mvc 路由,我会收到 403 禁止,因为它认为我正在尝试列出目录内容并且显然没有t 默认文件,因为该文件夹是虚拟的。

如果虚拟目录/应用程序是要走的路,我应该把它指向哪里?

标签: c#iisasp.net-mvc-5.2

解决方案


以下不是我正在寻找的解决方案。我想要一个无需任何编码或部署(即在 IIS 中)即可添加/删除/修改的非编程实现。我决定使用它的原因是因为它实施起来非常简单快捷。与我寻找和尝试 IIS 解决方案相比,实施所需的时间要少得多。

显然,这不适合大多数应用程序的安全性,但由于它易于实现,它非常适合我的场景

它是使用自定义 ActionFilter 和控制器上的属性的基本身份验证。

首先,创建您的 ActionFilter:

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 BasicAuthenticationAttribute()
    {
        this.Username = ConfigurationManager.AppSettings["UserName"];
        this.Password = ConfigurationManager.AppSettings["Password"];
        this.BasicRealm = ConfigurationManager.AppSettings["BasicRealm"];
    }

    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;
        }
        filterContext.HttpContext.Response.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? ""));
        filterContext.Result = new HttpUnauthorizedResult();
    }
}

然后,将属性添加到要保护的控制器:

[BasicAuthentication()]

或者如果您出于某种原因想对您的用户名和密码进行硬编码

[BasicAuthentication("username", "password", BasicRealm = "your-realm")]

就是这样。只需将凭据添加到您的 web.config 并根据需要创建自定义 401 错误页面。

我想如果您希望能够在不重新部署应用程序的情况下将其关闭,那么添加另一个 web.config 密钥作为激活以停用身份验证的标志也很容易


推荐阅读