0

So what is happening is that I have a condition within my override of the HandleUnauthorizedRequest method in my custom authorize attribute. Up to this point, I've been throwing a 403 which gets picked up and redirects to a custom error page. Well now, that's not really what I want. What I actually want is to show the same login page but add a message to the validation summary "You do not have access to this resource.", that way it's a bit more user friendly. It'll indicate that your creds were good, but you don't belong here.

I thought something like this would work:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    // passed authentication, failed authorization
    if (filterContext.HttpContext.User.Identity.IsAuthenticated)
    {           
        filterContext.Controller.ViewData.ModelState.AddModelError("", "Not Authorized");
        return;
    }

    base.HandleUnauthorizedRequest(filterContext);
}

But this isn't working. What's happening is that the login page simply reloads. So this makes me feel like I'm close, but I need that model error to show up.

Any ideas?

UPDATE: It would seem that the Controller that I'm adding an error to here is actually controller of whichever action had the attribute that led to here. I need to somehow add the error to the login controller. Not sure if that's even possible.

4

1 回答 1

1

您在这里调用基本方法:

base.HandleUnauthorizedRequest(filterContext);

如果您使用表单身份验证,此基本方法只会将您重定向到登录页面。重定向意味着来自客户端的新 HTTP 请求。当前上下文以及您存储在其中的任何内容都会丢失。好吧,更准确地说,基本方法返回一个 401 HTTP 状态代码,然后被 FormsAuthenticationModule 拦截,重定向到 web.config 中定义的登录页面。但是这个实现细节并不重要。

您可以做的是将自己重定向到登录页面,而不是将其留给基本方法。您可以通过将filterContext.Result属性设置为RedirectToRouteResult实例来做到这一点。在这种情况下,您可以将错误消息作为查询字符串参数传递。


更新:

根据您更新的问题,您似乎是return;在设置 ModelState 值之后调用而不是调用基本方法,因此登录 url 不会发生重定向。filterContext.Result在这种情况下,您可以通过将 设置为 a 的实例来返回一些错误视图,ViewResult您可以在其中使用存储在 ModelState 中的值。

于 2013-07-19T21:17:48.800 回答