简体   繁体   English

覆盖授权属性

[英]Overriding Authorize Attribute

I have a need to override authorize attribute. 我需要覆盖授权属性。

Basically if its an ajax request and the user is not logged in or is not in specified roles then i want to return a JSON. 基本上,如果其ajax请求和用户未登录或未处于指定角色,那么我想返回JSON。 The JSON will tell the caller the reason as not logged in or not in role and needs to return the redirect to url. JSON将告诉调用者未登录或未担任角色的原因,并且需要将重定向返回到url。 In case of not signed it, it also needs to give back ReturnUrl. 如果未签名,还需要退还ReturnUrl。

If its not an ajax request then i want the default processing by Authorize attribute to kick in. 如果不是ajax请求,那么我希望通过Authorize属性进行默认处理。

We are using forms authentication and the sign in url and error pages are specified in the web.config file. 我们正在使用表单身份验证,并且在web.config文件中指定了登录URL和错误页面。

Following is my take at it but i am not getting the following right 以下是我的看法,但我没有正确理解以下内容

  1. missing roles processing in case of an ajax request 在ajax请求的情况下缺少角色处理

  2. in case of not an ajax request (else block), i am redirecting the user to the sign in page. 在没有ajax请求(其他块)的情况下,我会将用户重定向到登录页面。 i want the default autorize attribute to kickin in this case 在这种情况下,我希望默认的autorize属性启动

I just need the push in the right direction... tutorial or a blog pointer is all i need to learn and accomplish this.... 我只需要朝着正确的方向努力...教程或博客指针就是我学习和完成此任务所需的全部...。

public class AuthorizePartnerProgramsAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            HttpContext httpContext = HttpContext.Current;


            var url = new UrlHelper(filterContext.RequestContext);

            var request = filterContext.HttpContext.Request;

            if (request.IsAuthenticated == false)
            {

                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    if (request.Url != null)
                        filterContext.Result = CommonUtilities.AddJsonUtf8Encoding(new JsonResult { Data = new { error = true, singinerror = true, message = "Sign in required!", returnUrl = request.UrlReferrer.AbsolutePath.ToString() } });
                    else
                        filterContext.Result = CommonUtilities.AddJsonUtf8Encoding(new JsonResult { Data = new { error = true, singinerror = true, message = "Sign in required!" } });
                }
                else
                {
                    if (request.UrlReferrer != null)
                    {
                        filterContext.Result = new RedirectResult(url.Action("Index", "SignIn", new { Area = "Account",  ReturnUrl = filterContext.RequestContext.HttpContext.Request.UrlReferrer.AbsolutePath.ToString() }));
                    }
                    else
                    {
                        filterContext.Result = new RedirectResult(url.Action("Index", "SignIn", new { Area = "Account"}));

                    }
                }

            }

        }


    }

Here is my second stab at it. 这是我的第二次尝试。 I think i am now more confused than before and need help setting it up properly 我想我现在比以前更困惑,需要帮助来正确设置它

public class AuthorizeCustomAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var request = filterContext.RequestContext.HttpContext.Request;

            if (request.IsAjaxRequest())
            {
                var url = new UrlHelper(filterContext.RequestContext);
                var urlReferer = request.UrlReferrer != null
                    ? request.UrlReferrer.ToString()
                    : String.Empty;
                var signInUrl = url.Action("Index", "SignIn", new { Area = "Account", ReturnUrl = urlReferer });
                var accessDeniedUrl = url.Action("PageAccessDenied", "Error", new { Area = "" });
                if (!request.IsAuthenticated)
                {
                    //not authenticated
                    filterContext.Result =
                        CommonUtilities.AddJsonUtf8Encoding(new JsonResult
                        {
                            Data =
                                new {error = true, singinerror = true, message = "Sign in required!", url = signInUrl},
                            JsonRequestBehavior = JsonRequestBehavior.AllowGet
                        });
                }
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext.Request.IsAjaxRequest())
            {
                //Use [AuthorizeCustom(Roles="MyRole1,MyRole2")]
                //or [AuthorizeCustom]
                //roles may not have been applied here

                //checking authentication will be done by the HandleUnauthorizedRequest?????
                //if no roles are specified then it is true = so give access to the resource
                //user may have multiple roles or single role assigned, check and if not in role then return json back. 
                //....
            }
            else
            {
                return base.AuthorizeCore(httpContext);
            }
        }
    }

This helped me setting up mine http://www.dotnet-tricks.com/Tutorial/mvc/G54G220114-Custom-Authentication-and-Authorization-in-ASP.NET-MVC.html 这有助于我设置我的http://www.dotnet-tricks.com/Tutorial/mvc/G54G220114-Custom-Authentication-and-Authorization-in-ASP.NET-MVC.html

use 采用

 [AuthorizeCustom(Roles = RoleNames.Admin)]

Here is the full working attribute for me without any cleanup. 这是我的全部工作属性,无需任何清理。

public class AuthorizeCustomAttribute : AuthorizeAttribute
    {
        #region CONSTANTS

        public const string SectionStemFuture = "StemFuture";

        #endregion


        #region PROPERTIES

        private string Section { get; set; }

        #endregion

        #region Constructor

        public AuthorizeCustomAttribute()
        {
            Section = String.Empty;
        }

        public AuthorizeCustomAttribute(string section)
        {
            Section = section;
        }

        #endregion

        #region Overrides

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var request = filterContext.HttpContext.Request;

            var url = new UrlHelper(filterContext.RequestContext);

            /*
            var urlReferer = request.UrlReferrer != null
                ? request.UrlReferrer.ToString()
                : String.Empty;
            */
            var urlReferer = request.Url.PathAndQuery;

            var signInUrl = url.Action("Index", "SignIn", new { Area = "Account", ReturnUrl = urlReferer });
            var accessDeniedUrl = url.Action("PageAccessDenied", "Error", new { Area = "" });

            //overwrite the default sign in URL according to the section
            if (!String.IsNullOrWhiteSpace(Section))
            {
                switch (Section)
                {
                    case SectionStemFuture:
                        signInUrl = url.Action("Index", "StemFutureHome", new { Area = "StemFuture", ReturnUrl = urlReferer });
                        break;
                }
            }


            if (!request.IsAuthenticated)
            {
                //not authenticated
                if (request.IsAjaxRequest())
                {
                    filterContext.Result =
                        CommonUtilities.AddJsonUtf8Encoding(new JsonResult
                        {
                            Data =
                                new {error = true, signinerror = true, message = "Sign in required", url = signInUrl},
                            JsonRequestBehavior = JsonRequestBehavior.AllowGet
                        });
                }
                else
                {
                    //this is not an ajax request
                    if (!String.IsNullOrWhiteSpace(Section))
                    {
                        filterContext.Result = new RedirectResult(signInUrl);
                    }
                    else
                    {
                        //let the base authorization take care of it
                        base.OnAuthorization(filterContext);    
                    }
                }

            }
            else if (!String.IsNullOrWhiteSpace(base.Roles))
            {
                var isRoleError = true;
                var rolesAllowed = base.Roles.Split(',');
                //authenticated and we have some roles to check against
                var user = filterContext.HttpContext.User;
                if (user != null && rolesAllowed.Any())
                {
                    foreach (var role in rolesAllowed)
                    {
                        if (user.IsInRole(role))
                        {
                            isRoleError = false;
                        }
                    }
                }

                if (isRoleError)
                {
                    if (request.IsAjaxRequest())
                    {
                        filterContext.Result =
                            CommonUtilities.AddJsonUtf8Encoding(new JsonResult
                            {
                                Data =
                                    new
                                    {
                                        error = true,
                                        signinerror = true,
                                        message = "Access denied",
                                        url = accessDeniedUrl
                                    },
                                JsonRequestBehavior = JsonRequestBehavior.AllowGet
                            });
                    }
                    else
                    {
                        //here we will need to pass to the access denied
                        filterContext.Result = new RedirectResult(accessDeniedUrl);
                    }
                }

            }

        }

        #endregion
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM