我想用密码保护我的MVC 5应用的路由之一。我不想经历Forms Auth或[Authorize]属性等的过程。我只想照常部署该应用程序,并使用IIS保护其中一条路由。
例如mydomain.com/
向世界开放
mydomain.com/Folder1
受保护的密码
使用IIS pwd保护物理文件夹是快速简便的,但是如果我创建一个虚拟目录或应用程序来匹配该mvc路由,则会收到403禁止,因为它认为我正在尝试列出目录内容,不是默认文件,因为该文件夹是虚拟的。
如果要使用虚拟目录/应用程序,该指向哪里?
以下不是我一直在寻找的解决方案。我想要一种无需编程即可实现的非编程实现,而无需进行任何编码或部署(即在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密钥作为标记来激活以停用身份验证,如果您希望能够在不重新部署应用程序的情况下将其关闭,也很容易。