ASP.NET MVC中的用户身份validation和授权

ASP.NET MVC中用户授权/authentication的最佳方法是什么?

我看到有两种方法:

  • 使用内置的ASP.NET授权系统。
  • 使用我自己的User,Permission,UserGroup表等自定义系统

我更喜欢第二种select,因为用户是我的领域模型的一部分(而且我对ASP.NET的内置东西没有经验),但我真的很想听听人们在这方面做了些什么。

实际上有第三种方法。 asp.net成员资格function基于提供者模型。 您可以编写自定义提供程序,从而能够提供自己的数据存储实现,但保留了asp.net成员资格的许多好处。

关于这个问题的一些文章:

http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx

http://www.asp.net/learn/videos/video-189.aspx

http://www.15seconds.com/issue/050216.htm

http://davidhayden.com/blog/dave/archive/2007/10/11/CreateCustomMembershipProviderASPNETWebsiteSecurity.aspx

去定制。 MembershipProvider对我的口味太重了。 是的,可以用简化的方式来实现它,但是你会得到一个非常糟糕的NotSupportedException或者NotImplementedExceptionexception。

完全自定义的实现,你仍然可以使用IPrincipal,IIdentity和FormsAuth。 真的有多难,你自己的login页面等?

最简单的方法是使用asp.net用户名作为angular色名称。 您可以编写自己的authorizarion属性来处理授权:

public class CustomAuthorizationAttribute:AuthorizeAttribute { public CustomAuthorizationAttribute():base() { Users = "registereduser"; } protected override bool AuthorizeCore(HttpContextBase httpContext) { //You must check if the user has logged in and return true if he did that. return (bool)(httpContext.Session["started"]??false); } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.HttpContext.Response.Redirect("SessionManagement/Index/?returningURL=" + filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.ToString())); } } 

如果用户启动了会话,代码必须处理AuthorizeCore返回true,HandleUnauthorizedRequest将用户redirect到login页面(可选地,您可以附加返回的url)。

然后在需要授权的控制器方法中,设置它们的属性:

 public class SecretPageController { [CustomAuthorizationAttribute] ActionResult Index() { //Method that requires authorization return View(); } } 

在Webconfiguration中将授权方法设置为“Forms”。

Web.config文件:

  <authentication> <forms timeout="120"></forms> </authentication> 

控制器:

 public SessionManagementController:Controller { public ActionResult Index(string returningURL) { return View("Index", new SessionModel() { ReturningURL = returningURL}); } [HttpPost] public ActionResult Index(SessionModel mod) { if (UserAuthenticated(mod.UserName, mod.Password)) { FormsAuthentication.SetAuthCookie("registereduser", false); if (mod.UrlRetorno != null) { return Redirect(mod.ReturningURL); } return RedirectToAction("Index", "StartPage"); } mod.Error = "Wrong User Name or Password"; return View(mod); } bool UserAuthenticated(string userName, string password) { //Write here the authentication code (it can be from a database, predefined users,, etc) return true; } public ActionResult FinishSession() { HttpContext.Session.Clear();//Clear the session information FormsAuthentication.SignOut(); return View(new NotificacionModel() { Message = "Session Finished", URL = Request.Url.ToString() }); } } 

在Controller中,当用户input用户名和密码时,将表单authenticationcookie设置为TRUE(FormsAuthentication.SetAuthCookie(“registereduser”,true)),用信号通知用户名(在本例中为注册用户)进行authentication。 然后用户注销,告诉ASP.NET这样做调用FormsAuthentication.SignOut()。

模型:

 class SessionModel { public string UserName {get;set;} public string Password {get;set;} public string Error {get;set;} } 

使用模型来存储用户数据。

查看(显示SessionModeltypes):

  <div class="editor-label"> <%: Html.LabelFor(model => model.UserName) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.UserName) %> <%: Html.ValidationMessageFor(model => model.UserName) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.Password) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.Password) %> <%: Html.ValidationMessageFor(model => model.Password) %> </div> <div class="field-validation-error"><%:Model==null?"":Model.Error??"" %></div> <%:Html.HiddenFor(model=>model.ReturningURL) %> <input type="submit" value="Log In" /> 

使用视图来获取数据。 在这个例子中,有一个隐藏字段来存储返回的URL

我希望这有助于(我必须翻译的代码,所以我不知道它是否是100%正确的)。

另一种方法是使用ASP.NET成员进行身份validation,将您的User类链接到ASP.NET成员,并使用您的User类获取更细化的权限。 我们这样做是因为它允许非常容易地更改身份validation提供程序,同时仍保留具有复杂权限系统的function。

一般来说,值得记住的是authentication/身份和存储权限不一定是同一个问题。

您可能会对RPX感兴趣,获得一个免费的API来validation您的用户

http://blog.maartenballiauw.be/post/2009/07/27/Authenticating-users-with-RPXNow-(in-ASPNET-MVC).aspx

尝试pipe理API的ASP.Net MVC成员初学者工具包

截图

http://www.squaredroot.com/2009/08/07/mvcmembership-release-1-0/

旧地点变更集(历史)

http://mvcmembership.codeplex.com/SourceControl/list/changesets

新地点:

http://github.com/TroyGoode/MembershipStarterKit

这是第四种方法。 使用networkingmatrix安全类,您可以使用简单的成员资格提供程序,可以使用EF,因此用户和angular色可以成为您的域模型的一部分,但也是IPrincipal和IIdentity MVC助手的一部分。

我创build了一个示例Github项目,以了解如何使用自动注册和电子邮件注册/密码重置等。