joh*_* Gu 3 asp.net iis authorize-attribute asp.net-mvc-4
我正在使用asp.net mvc 4 Web应用程序,我编写了以下自定义授权类: -
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CheckUserPermissionsAttribute : AuthorizeAttribute
{
public string Model { get; set; }
public string Action { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.Request.IsAuthenticated)
return false;
//code goes here
if (!repository.can(ADusername, Model, value)) // implement this method based on your tables and logic
{
return false;
//base.HandleUnauthorizedRequest(filterContext);
}
return true;
// base.OnAuthorization(filterContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
var viewResult = new JsonResult();
viewResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
viewResult.Data = (new { IsSuccess = "Unauthorized", description = "Sorry, you do not have the required permission to perform this action." });
filterContext.Result = viewResult;
}
else
{
var viewResult = new ViewResult();
viewResult.ViewName = "~/Views/Errors/_Unauthorized.cshtml";
filterContext.Result = viewResult;
}
base.HandleUnauthorizedRequest(filterContext);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但我现在面临的唯一问题是,如果授权失败,则会提示用户输入用户名和密码,尽管我已根据请求是否为AJAX覆盖HandleUnauthorizedRequest以返回视图或JSON.那么你可以建议为什么在授权失败时提示用户输入他的用户名和密码,而不是接收_unauthorized视图或包含错误消息的JSON
但我现在面临的唯一问题是,如果授权失败,则会提示用户输入用户名和密码,尽管我已根据请求是否为AJAX覆盖HandleUnauthorizedRequest以返回视图或JSON.
那是因为你绝对总是在你的HandleUnauthorizedRequest
方法中点击以下行:
base.HandleUnauthorizedRequest(filterContext);
Run Code Online (Sandbox Code Playgroud)
你知道这行是做什么的吗?它调用基本方法.你知道基本方法的作用吗?它返回401状态代码.您知道在使用Forms身份验证的ASP.NET应用程序中返回401状态响应代码时会发生什么?您将获得登录页面.
所以,是的,如果你正在使用AJAX或其他东西,并打算返回一些JSON或东西,请确保永远不会调用基本的东西.顺便说一下,在你的else
情况下,你似乎试图渲染一些~/Views/Errors/_Unauthorized.cshtml
显然无用的视图,因为你也在调用基本方法,它只是重定向到登录页面.
我认为在我的答案的这个阶段你已经知道该怎么做了:摆脱你的HandleUnauthorizedRequest
方法的最后一行,你通过调用基本方法将所有的努力投入垃圾箱.
如果你想正确地做事并返回401状态代码而不是获取登录页面,而是返回一些自定义JSON,你可以使用SuppressFormsAuthenticationRedirect
Response对象上的属性.如果您使用的是没有此属性的.NET框架的旧版本,您可能会发现following blog post
Phil Haack解释如何处理此案例的有用信息.
归档时间: |
|
查看次数: |
3633 次 |
最近记录: |