c# - 如何使用 IIS 对 MVC 路由进行密码保护
问题描述
我想密码保护我的 MVC 5 应用程序的路线之一。我不想经历 Forms Auth 或 [Authorize] 属性等过程。我只想像往常一样部署应用程序并使用 IIS 来保护其中一个路由。
egmydomain.com/
对世界开放
mydomain.com/Folder1
密码保护
使用 IIS pwd 保护物理文件夹既快速又简单,但是如果我创建一个虚拟目录或应用程序来匹配该 mvc 路由,我会收到 403 禁止,因为它认为我正在尝试列出目录内容并且显然没有t 默认文件,因为该文件夹是虚拟的。
如果虚拟目录/应用程序是要走的路,我应该把它指向哪里?
解决方案
以下不是我正在寻找的解决方案。我想要一个无需任何编码或部署(即在 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 密钥作为激活以停用身份验证的标志也很容易
推荐阅读
- python-3.x - 如何获得程序的控制流程图?
- ios - 按名称获取sqlite查询结果 - Objective C
- c# - Azure 应用服务上的反恶意软件
- django - 如何在 django 中默认设置用户为员工
- apache-spark - 将环境变量传递给 YARN 容器
- graphql - 是否可以根据条件返回 GraphQL 中的字段?
- exchange-server - 使用 EWS 检索所有 Exchange 联系人(全局地址列表和用户联系人文件夹)
- maven - Jenkins 插件开发:使用哪个版本的依赖项?
- ag-grid - Ag-Grid 详细(子)网格未导出
- android - 更新数据库时如何从 Firebase 发送电子邮件通知