如果您只是想确保有限的受众(例如测试用户)可以访问您的网站,最简单的方法是在现有身份验证之上添加基本或摘要身份验证。
ActionFilterAttribute
如果您的部署场景(生产与登台等)需要保护,请将其实现为一个并将其添加到您的全局过滤器集合中:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
bool basicAuthenticationEnabled = true; // AppSettings etc.
if (basicAuthenticationEnabled)
filters.Add(new BasicAuthenticationAttribute());
filters.Add(new HandleErrorAttribute())
}
相应BasicAuthenticationAttribute
类的实现可能如下所示:
public class BasicAuthenticationAttribute : ActionFilterAttribute
{
private const string Realm = "MyRealm";
private const string UserName = "MyUserName";
private const string Password = "MyPassword";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var authorizationHeader = filterContext.RequestContext.HttpContext.Request.Headers["Authorization"];
if (authorizationHeader != null && authorizationHeader.StartsWith("Basic"))
{
var credentials = Encoding.ASCII.GetString(
Convert.FromBase64String(authorizationHeader.Substring(6))
).Split(':');
if (credentials[0].Equals(UserName) && credentials[1].Equals(Password))
{
base.OnActionExecuting(filterContext);
return;
}
}
// send require authentication
var response = filterContext.HttpContext.Response;
response .StatusCode = 401;
response .AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", Realm));
response .End();
}
}
无论如何,我强烈建议使用摘要式身份验证,因为它在通过网络发送密码之前将哈希函数应用于密码,这比发送明文的基本访问身份验证更安全。
你可以在这里找到一个DigestAuthorizationAttribute
类的实现和更多信息: