在ASP.NET MVC定制授权 [英] Customizing authorization in ASP.NET MVC

查看:181
本文介绍了在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" he is automatically redirected to the login page with a url like this:

<一个href=\"http://localhost:1436/Account/Login?ReturnUrl=%2fBuy\">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.

我能做些什么来定制这种行为?
是否有可能需要的用户级别传递给登录动作不知?

What can I do to customize this behavior? 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是HttpUnauthorizedResult似乎是不够的:<一href=\"http://stackoverflow.com/questions/505653/what-happened-to-filtercontext-cancel-asp-net-mvc/505679#505679\">What碰巧filterContext.Cancel(ASP.NET MVC)

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

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