自定义授权属性,重定向到原始URL

时间:2017-06-19 15:35:26

标签: asp.net-mvc redirect attributes authorization

我以前一直使用我自己的类和if语句来处理角色/访问权限,其中用户的原始URL保存,但他甚至没有登录。一旦用户登录,他就被重定向到他的原始页面。现在下面是我的旧代码。我在自定义授权属性中使用相同的逻辑很困难。请指导。谢谢

(旧方法)每个动作方法中的包装器

[HttpGet]
        public ActionResult Index(string DealType)
        {
            User user = Session["CurrentUser"] as User;
            if (user != null)
            {
                if (user.IsInRole(RoleType.MASTER) || user.IsInRole(RoleType.VIEW))
                {
                    // Money Shot
                    List<Deal> deals = dataBase.Deals.Where(d => d.DealType.Equals(DealType)).ToList();

                    return View(deals);
                }
                else
                {
                    return PartialView("_unauthorize");
                }
            }
            else
            {
// I need to handle this part in custom attribute
                return RedirectToAction("Login", "User", new { RedirectURL= string.Format("/{0}/{1}", "Deal", "Index") });
            }
        } 

在我的登录操作方法中,我使用了这个

public ActionResult Login(User model){
//Code of matching username and password...
//Validations/ exceptions handling of incorrect passwords

 if (!string.IsNullOrEmpty(RedirectURL))
                            {
                                return Redirect(RedirectURL);
                            }
                            else
                            {
                                return RedirectToAction("Index", "Home");
                            }
}

现在,我了解了自定义属性,我将其应用于下面

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    public AuthorizeUserAttribute(params RoleType[] roleTypes)
    {
        AccessLevels = roleTypes;
    }

    // Custom property
    public RoleType[] AccessLevels { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        User user = HttpContext.Current.Session["CurrentUser"] as User;

        if (user != null)
        {
            if (user.IsInRole(AccessLevels))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
//redirect URL should be save here but this is boolean method!
                return false;
            }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary(
                        new
                        {
                            controller = "User",
                            action = "Unauthorised"
                        })
                    );
    }
}

我像这样使用它们

[AuthorizeUser(RoleType.DELETE, RoleType.ADMIN)]

现在的问题是,如果用户完全没有登录他正在访问的URL应该保存,一旦他登录,他应该被重定向到他来自的地方。希望我解释得很好。

1 个答案:

答案 0 :(得分:1)

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            RedirectToRouteResult routeData = null;
            var returnUrl = string.Empty;

            if(filterContext.HttpContext.Request.Url != null)
                 returnUrl = filterContext.HttpContext.Request.Url.LocalPath;

            if (CurrentUser == null)
                routeData = new RedirectToRouteResult(
                    new RouteValueDictionary(new {controller = "Account", action = "Login", returnUrl = returnUrl}));
            else
                routeData = new RedirectToRouteResult(
                    new RouteValueDictionary(new {controller = "Error", action = "AccessDenied"}));

            filterContext.Result = routeData;
        }

在上面的代码中(在您的自定义AuthorizeAttribute内部),您可以使用可用的请求信息捕获返回URL。

这将使您的returnUrl在Request.QueryString []词典中可用。

在“登录”视图上,您​​需要添加类似内容以使其可操作。

@{
    ViewBag.ReturnUrl = Request.QueryString["returnUrl"];
}

,然后在您的登录表单中:

@using (Html.BeginForm("Login", "Account", new {returnUrl = ViewBag.ReturnUrl}, FormMethod.Post, new{@class="form-horizontal form-material", @onsubmit="return loading_event();", @id="loginForm"}))