ASP.NET MVC 5中的身份验证和授权

23

ASP.Net MVC 5貌似已经放弃使用AuthorizeAttribute类,您可以通过实现AuthorizeAttribute类并重写其方法以及隐藏SiteRole属性来创建自定义授权属性,以便在其中添加自己的角色。所有我看到的示例都建议使用OWIN或Identity Framework。这两种方式是在新的ASP.Net框架中执行身份验证和授权的唯一两种方式吗?如果我按照传统的方式来做,是否会错过什么?我不想让框架为我创建所有用户和角色表。如果我想要将现有的用户和角色表添加到新应用程序中,该怎么办?

我也真的不认为每个应用程序都需要社交集成,而且我也不认为我会立即需要它。有没有一篇文章解释如何使用自定义授权属性开始,并逐步添加新的身份验证功能。我希望找到一个基本解释了新创建项目中选择“无身份验证”或“单个用户身份验证”时的所有混乱部分的文章。

2个回答

23
您可以使用ASP.NET Identity在MVC 5中自定义AuthorizeAttribute。这个SimpleSecurity项目中有一个实现示例。这里有一个用于控制器的定制化AuthorizedAttribute,以及这里有一个用于Web API的定制化AuthorizeAttribute。这些定制化AuthorizeAttributes背后的概念是将安全模型与应用程序模型解耦,这在此处讨论。Web API的那个还支持基本身份验证

随着OWIN的引入,安全管道已经发生了变化。我在Web API的AuthorizeAttribute行为方面遇到了一些问题,这在这里讨论

您还可以在SimpleSecurity项目中找到有关将旧会员提供程序SimpleMembership移植到MVC 5的示例。其中一些升级过程中的问题在这里讨论。但是我确实让它工作了,所以您可以选择旧的会员提供程序实现。但我的建议是使用ASP.NET Identity,因为这是Microsoft未来支持的方式,它具有更灵活的架构,并消除了许多在旧会员提供程序实现中发现的问题


+1 非常棒的资源,特别是SimpleSecurity项目。谢谢! - Shay
@Kevin Junghans 我仍然无法在MVC 5中添加自定义的 AuthorizeAttribute。我创建了 public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute { ... },但是我无法在我的控制器中使用它。 - mhesabi
@mhesabi - 你需要提供更多关于你的问题以及如何实现自定义授权属性的具体信息,才能得到帮助。我建议你在详细说明中包含代码片段,开启一个QA,并在这里留下指向新QA的评论。 - Kevin Junghans

0

Ben Foster有一个两部分的系列文章,带你从零开始实现基于cookie的ASP.NET Identity身份验证步骤,从没有选择身份验证的新Web应用程序开始。跟随“ASP.NET Identity Stripped Bare”Part 1Part 2

使用以下Authorize属性来处理已经经过身份验证的用户未经授权访问。

public class LoggedOrAuthorizedAttribute : AuthorizeAttribute 
{ 
   public LoggedOrAuthorizedAttribute() 
    { 
       View = "error"; 
       Master = String.Empty; 
    } 

    public String View { get; set; } 
    public String Master { get; set; } 

public override void OnAuthorization(AuthorizationContext filterContext) 
{ 
  base.OnAuthorization(filterContext); 
  CheckIfUserIsAuthenticated(filterContext); 
} 

   private void CheckIfUserIsAuthenticated(AuthorizationContext filterContext) 
{ 
   // If Result is null, we’re OK: the user is authenticated and authorized. 
   if (filterContext.Result == null) 
      return; 

   // If here, you’re getting an HTTP 401 status code. In particular,
   // filterContext.Result is of HttpUnauthorizedResult type. Check Ajax      here. 
   if (filterContext.HttpContext.User.Identity.IsAuthenticated) 
    { 
      if (String.IsNullOrEmpty(View)) 
         return; 
      var result = new ViewResult {ViewName = View, MasterName = Master}; 
      filterContext.Result = result; 
   } 
 }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接