这是我的基本控制器的代码,我们的想法是,如果Authorization字符串不在HTTP Headers中,我们就会将它们踢出去。我发誓它工作正常,现在突然它不起作用。奇怪的是,当我调试它实际上是在INTO if语句中,所以我请求的HTTP Header确实是一个NULL或EMPTY字符串,但是,它没有提前退出并且返回403 Access Denied了...它正在工作很好,突然间它只是忽略了整个事情,并在我尝试解析未实际发现的授权字符串时最终在应用程序中崩溃。
public class AuthController : Controller
{
protected int AccountID;
protected override void OnAuthorization(AuthorizationContext filterContext)
{
//if no authorization string is provided, access denied
if (string.IsNullOrEmpty(filterContext.HttpContext.Request.Headers["Authorization"]))
{
filterContext.Result = Content("Access Denied", "text/plain");
filterContext.HttpContext.Response.StatusCode = 403; //forbidden
base.OnAuthorization(filterContext);
}
//otherwise grab the authorization string and validate it
string authString = filterContext.HttpContext.Request.Headers["Authorization"];
string urlPath = string.IsNullOrEmpty(filterContext.HttpContext.Request.Path) ? "" : filterContext.HttpContext.Request.Path;
int getAccountID = 0;
//if authorization fails...
if (!AuthCore.Authorize(authString, urlPath, ref getAccountID))
{
filterContext.Result = Content("Access Denied", "text/plain");
filterContext.HttpContext.Response.StatusCode = 403; //forbidden
base.OnAuthorization(filterContext);
}
//AccountID will never be zero at this point
AccountID = getAccountID;
//carry on with Controller Action, request is valid and AccountID is known
base.OnAuthorization(filterContext);
}
UPDATE :刚试过filterContext.Result = new HttpUnauthorizedResult();相反,相同的结果。控制器操作继续并在尝试解析未找到的标头字符串时抛出错误。
更新2 :添加“返回”在每个base.OnAuthorization()之后调用除了最后一个之后,现在当它失败时我得到一个302从MVC移动后跟404,结果是应用程序试图重定向到一个实际上没有的默认登录页面URL存在......这可能足够好吗?也许,但我宁愿直接阻止它,而不是让一些不稳定的重定向发生,因为阻止它们的方式,对我来说并不安全。
答案 0 :(得分:1)
啊哈!
我正在调用base.OnAuthorization()太多次了,显然它实际上并不是线程的永久告别......不知道为什么我认为现在我想起来了......这是工作代码:
protected override void OnAuthorization(AuthorizationContext filterContext)
{
int getAccountID = 0;
//if no authorization string is provided, access denied
if (string.IsNullOrEmpty(filterContext.HttpContext.Request.Headers["Authorization"]))
{
filterContext.Result = Content("Access Denied", "text/plain");
filterContext.HttpContext.Response.StatusCode = 403; //forbidden
}
else
{
//otherwise grab the authorization string and validate it
string authString = filterContext.HttpContext.Request.Headers["Authorization"];
string urlPath = string.IsNullOrEmpty(filterContext.HttpContext.Request.Path) ? "" : filterContext.HttpContext.Request.Path;
//if authorization fails...
if (!AuthCore.Authorize(authString, urlPath, ref getAccountID))
{
filterContext.Result = Content("Access Denied", "text/plain");
filterContext.HttpContext.Response.StatusCode = 403; //forbidden
}
}
//AccountID will never be zero at this point
AccountID = getAccountID;
//carry on with Controller Action, request is valid and AccountID is known
base.OnAuthorization(filterContext);
}
答案 1 :(得分:0)
我想你应该查看这篇文章: Securing your ASP.NET MVC 3 Application