gpt4 book ai didi

c# - 当用户不在授权角色中时,如何提供未授权页面?

转载 作者:IT王子 更新时间:2023-10-29 03:57:43 25 4
gpt4 key购买 nike

我正在使用这样的 Authorize 属性:

[Authorize (Roles="Admin, User")]
Public ActionResult Index(int id)
{
// blah
}

当用户不属于指定角色时,我会收到一个错误页面(找不到资源)。所以我也将 HandleError 属性放入。

[Authorize (Roles="Admin, User"), HandleError]
Public ActionResult Index(int id)
{
// blah
}

现在,如果用户不在指定的角色中,它将转到登录页面。

当用户不满足所需角色之一时,如何让它转到未授权页面而不是登录页面?如果发生不同的错误,我如何区分该错误与未经授权的错误并以不同方式处理它?<​​/p>

最佳答案

将这样的东西添加到您的 web.config 中:

<customErrors mode="On" defaultRedirect="~/Login">
<error statusCode="401" redirect="~/Unauthorized" />
<error statusCode="404" redirect="~/PageNotFound" />
</customErrors>

您显然应该创建 /PageNotFound/Unauthorized 路由、操作和 View 。

编辑:对不起,我显然没有彻底理解这个问题。

问题在于,当执行 AuthorizeAttribute 过滤器时,它确定用户不符合要求(他/她可能已登录,但角色不正确)。因此它将响应状态代码设置为 401。这将被 FormsAuthentication 模块拦截,然后执行重定向。

我看到了两种选择:

  1. 禁用默认重定向。

  2. 创建您自己的 IAuthorizationFilter。从 AuthorizeAttribute 派生并覆盖 HandleUnauthorizedRequest。在此方法中,如果用户通过身份验证,则重定向到/Unauthorized

我也不喜欢:defaultRedirect 功能很好,不是你想自己实现的东西。第二种方法会导致向用户提供视觉上正确的“您未被授权”页面,但 HTTP 状态代码将不是所需的 401。

我对 HttpModules 的了解还不够,无法确定是否可以通过可容忍的 hack 来规避这种情况。

编辑 2:如何通过以下方式实现您自己的 IAuthorizationFilter:从 CodePlex 下载 MVC2 代码并“借用”AuthorizeAttribute 的代码。将 OnAuthorization 方法更改为如下所示

    public virtual void OnAuthorization(AuthorizationContext filterContext)
{
if (AuthorizeCore(filterContext.HttpContext))
{
HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge(new TimeSpan(0));
cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
}
// Is user logged in?
else if(filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// Redirect to custom Unauthorized page
filterContext.Result = new RedirectResult(unauthorizedUrl);
}
else {
// Handle in the usual way
HandleUnauthorizedRequest(filterContext);
}
}

其中 unauthorizedUrl 是过滤器上的属性或从 Web.config 中读取。

您也可以从 AuthorizeAttribute 继承并覆盖 OnAuthorization,但您最终会编写几个已经在 AuthorizeAttribute 中的私有(private)方法。

关于c# - 当用户不在授权角色中时,如何提供未授权页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2322366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com