【问题标题】:How do I password protect an MVC route with IIS如何使用 IIS 对 MVC 路由进行密码保护
【发布时间】:2020-04-22 23:14:00
【问题描述】:

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

例如mydomain.com/向世界开放

mydomain.com/Folder1密码保护

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

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

【问题讨论】:

  • IIS 没有像其他 Web 服务器那样的任何“密码保护”功能。您必须使用适当的身份验证方法(如表单或其他)。
  • 您绝对可以使用 IIS 在网站或文件夹上添加身份验证。我做到了

标签: c# iis asp.net-mvc-5.2


【解决方案1】:

以下不是我正在寻找的解决方案。我想要一个无需任何编码或部署(即在 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 密钥作为激活标志以停用身份验证也很容易

【讨论】:

    猜你喜欢
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 2020-11-28
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    相关资源
    最近更新 更多