【发布时间】:2014-08-06 16:59:37
【问题描述】:
我在我的 asp.net mvc 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; }
return true;
}
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);
}
}
我在我的操作方法之前调用这个自定义授权如下:-
[CheckUserPermissions(Action = "Read", Model = "Accounts")]
public ActionResult Index(){
目前在上述代码中看到请求未授权时,我会根据请求类型(是否为Ajax请求)返回JSON或部分视图。
在我的代码中,我总是负责处理从 onsuccess 脚本中的自定义授权类返回的 json,如下所示:-
function addrecords(data) {
if (data.IsSuccess == "Unauthorized") {
jAlert(data.description, 'Unauthorized Access');
}
else if (data.IsSuccess) {
jAlert(data.description, 'Creation Confirmation');
}
目前我的方法运行良好,但我开始考虑是否应该继续这样一个事实,即我不会为未经授权的请求重新调整 401 http 响应?而不是我返回一个 http 200 ,或者作为状态 =“未授权”的 json 对象或重定向到部分视图?
谁能给点建议?
谢谢。
【问题讨论】:
标签: c# asp.net asp.net-mvc asp.net-mvc-5 authorize-attribute