在 ASP.NET MVC 中自定义授权 [英] Customizing authorization in ASP.NET MVC

查看:31
本文介绍了在 ASP.NET MVC 中自定义授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器类装饰有 AuthorizeAttribute 以保护操作:

My Controller class is decorated with an AuthorizeAttribute to protect the actions:

[Authorize(Roles = "User Level 2")]
public class BuyController : Controller
{
    ...
}

任何时候调用操作,但用户至少不是用户级别 2"角色,用户会自动重定向到登录页面,网址如下:

Anytime an action is invoked, but the user is not in at least the role "User Level 2", the user is automatically redirected to the login page with a URL like this:

http://localhost:1436/Account/Login?ReturnUrl=%2fBuy

如果用户已经登录,但没有正确的安全级别,这不是最佳行为!显示一个页面来通知用户缺少的级别而不是显示登录页面会更有意义.

If the user is already logged in, but doesn't have the right security level, this is not an optimal behavior! It would make more sense to display a page which informs the user about the missing level instead of showing the login page.

如何自定义此行为?

是否可以以某种方式将所需的用户级别传递给登录操作?

Is it possible to pass the required user level to the Login action somehow?

推荐答案

您可以像这样构建自己的授权属性:

You can build your own authorize attribute like this:

public class ClubAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
  base.OnAuthorization(filterContext);
  if (filterContext.Cancel && filterContext.Result is HttpUnauthorizedResult)
  {
    filterContext.Result = new RedirectToRouteResult(
      new RouteValueDictionary {
      { "clubShortName", filterContext.RouteData.Values[ "clubShortName" ] },
      { "controller", "Account" },
      { "action", "Login" },
      { "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
    });
  }
}
}

我用它重定向到我正在建立的俱乐部会员网站中的特定俱乐部.您可以根据自己的需要进行调整.顺便说一句,在我的情况下,我确实重定向到登录页面,但我检查用户是否已获得授权,如果是,则显示一条消息,表明他们没有正确的权限.毫无疑问,您也可以向 ViewData 或 TempData 添加一些内容以显示在页面上,但我还没有尝试过

I used this to redirect to a specific club in a club membership site I am building. You could adapt this to your need. BTW, in my case I do redirect to the login page, but I check to see if the user is authorized and if so, display a message that they don't have the correct permissions. No doubt you could also add something to ViewData or TempData to display on the page, but I haven't tried that

编辑AuthorizationContext.Cancel 在 RC 中不再存在.filterContext.Result is HttpUnauthorizedResult"似乎就足够了:filterContext.Cancel (ASP.NET MVC) 发生了什么

EDIT AuthorizationContext.Cancel doesn't exist anymore in RC. "filterContext.Result is HttpUnauthorizedResult" seems to be enough : What happened to filterContext.Cancel (ASP.NET MVC)

这篇关于在 ASP.NET MVC 中自定义授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆