【问题标题】:ASP .NET MVC Secure all resourcesASP .NET MVC 保护所有资源
【发布时间】:2010-04-01 07:02:11
【问题描述】:

如何在整个控制器上启用身份验证并仅对某些操作方法禁用。我想要对所有资源进行身份验证。如果我写这样的东西:

[Authorize]
public class HomeController : BaseController
{
    //This is public
    [UnAuthorized]
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        return View();
    }
    //This is private resource
    public ActionResult PrivateResource()
    {
        return View();
    }
}

然后任何人都可以访问此资源。我需要这个,因为我们的所有资源都是私有的,在我们的项目中很少是公开的。你有什么想法可以让它变得更好吗?

【问题讨论】:

标签: c# asp.net-mvc authentication


【解决方案1】:

相应地组织您的控制器。为所有经过身份验证的资源提供一个基本控制器,您可以使用 [Authorize] 属性进行注释,另一个用于公共资源。

[Authorize]
public abstract BaseAuthenticatedController : Controller
{ }

public abstract BaseController : Controller
{ }

【讨论】:

  • 谢谢达林。这不是我想要的。我希望能够将控制器的某些操作方法设为公开,其余的设为私有。
【解决方案2】:

根据here 找到的解决方案,我编写了完全符合我要求的代码。

根据 AuthorizeAttribute 创建自定义授权属性并覆盖 OnAuthorization 方法:

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext != null)
        {
            object[] attributes = filterContext.ActionDescriptor.GetCustomAttributes(false);
            if (attributes != null)
            {
                foreach (var attribute in attributes)
                    if (attribute is UnAuthorizedAttribute)
                        return;
            }
        }
        base.OnAuthorization(filterContext);
    }

我在这里使用反射来识别具有 UnAuthorized 属性的操作。我不知道这种情况下的性能问题,但它完全解决了问题。

【讨论】:

  • 这段代码大部分是不必要的。直接使用 ActionDescriptor.GetCustomAttributes() 就可以了,这样就可以绕过使用反射来猜测传入的方法是什么。
猜你喜欢
  • 1970-01-01
  • 2013-10-02
  • 2014-05-05
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多