ASP.NET MVC 中的用户身份验证和授权
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/524086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
User authentication and authorisation in ASP.NET MVC
提问by Neil Barnwell
What is the best method for user authorisation/authentication in ASP.NET MVC?
ASP.NET MVC 中用户授权/身份验证的最佳方法是什么?
I see there are really two approaches:
我看到确实有两种方法:
- Use the built-in ASP.NET authorisation system.
- Use a custom system with my own User, Permission, UserGroup tables etc.
- 使用内置的 ASP.NET 授权系统。
- 使用带有我自己的用户、权限、用户组表等的自定义系统。
I'd prefer the second option, because User is part of my domain model (and I have zeroexperience with ASP.NET's built-in stuff), but I'd really like to hear what people have been doing in this area.
我更喜欢第二个选项,因为 User 是我的域模型的一部分(我对ASP.NET 的内置内容的经验为零),但我真的很想听听人们在这方面做了什么。
采纳答案by Jim Petkus
There is actually a third approach. The asp.net membership functionality is based on the provider model. You can write a custom provider, thus being able to provide your own implementation for how the data is stored, but retaining much of the benefit of asp.net membership.
其实还有第三种方法。asp.net 成员资格功能基于提供者模型。您可以编写自定义提供程序,从而能够为数据的存储方式提供您自己的实现,同时保留 asp.net 成员资格的大部分好处。
Some articles on the subject:
关于这个主题的一些文章:
http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx
http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx
http://www.asp.net/learn/videos/video-189.aspx
http://www.asp.net/learn/videos/video-189.aspx
http://www.15seconds.com/issue/050216.htm
回答by Tim Scott
Go with custom. MembershipProvider is way too heavy for my tastes. Yes it's possible to implement it in a simplified way, but then you get a really bad smellof NotSupportedException or NotImplementedException.
随风而去。MembershipProvider 对我的口味来说太重了。是的,可以以简化的方式实现它,但随后您会闻到 NotSupportedException 或 NotImplementedException 的味道。
With a totally custom implementation you can still use IPrincipal, IIdentity and FormsAuth. And really how hard is it do your own login page and such?
通过完全自定义的实现,您仍然可以使用 IPrincipal、IIdentity 和 FormsAuth。做你自己的登录页面等真的有多难?
回答by jesusdario
The easiest way is to use asp.net user names as role names. You can write your own authorizarion attribute to handle authorization:
最简单的方法是使用 asp.net 用户名作为角色名。您可以编写自己的授权属性来处理授权:
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()));
}
}
The code must handle the AuthorizeCore to return true if the user has started the session, and HandleUnauthorizedRequest to redirect the user to the login page (optionaly you can attach the returning url).
如果用户已启动会话,代码必须处理 AuthorizeCore 以返回 true,并处理 HandleUnauthorizedRequest 以将用户重定向到登录页面(您可以选择附加返回的 url)。
In then controller methods that need authorization, set the attribute over them:
在需要授权的控制器方法中,在它们上设置属性:
public class SecretPageController {
[CustomAuthorizationAttribute]
ActionResult Index() {
//Method that requires authorization
return View();
}
}
Also set the authorization method to "Forms" in the web config.
还要在 Web 配置中将授权方法设置为“表单”。
Web.config:
网页配置:
<authentication>
<forms timeout="120"></forms>
</authentication>
Controller:
控制器:
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() });
}
}
In the Controller, when the user enters its user name and password, set the forms authentication cookie to TRUE (FormsAuthentication.SetAuthCookie("registereduser",true)), signaling the user name (registereduser in the example) to be authenticathed. Then the user signs out, tell ASP.NET to do so calling FormsAuthentication.SignOut().
在控制器中,当用户输入其用户名和密码时,将表单身份验证 cookie 设置为 TRUE (FormsAuthentication.SetAuthCookie("registereduser",true)),表示用户名(在示例中为 registereduser)进行身份验证。然后用户注销,告诉 ASP.NET 这样做调用 FormsAuthentication.SignOut()。
Model:
模型:
class SessionModel {
public string UserName {get;set;}
public string Password {get;set;}
public string Error {get;set;}
}
Use a model to store the user data.
使用模型来存储用户数据。
View (that presents the SessionModel type):
视图(显示 SessionModel 类型):
<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" />
Use a view to get the data. In this example, there is a hidden field to store the returning URL
使用视图获取数据。在这个例子中,有一个隐藏字段来存储返回的 URL
I hope this helps (I had to translate the code, so I'm not sure if it is 100% correct).
我希望这会有所帮助(我必须翻译代码,所以我不确定它是否 100% 正确)。
回答by Craig Stuntz
Yet another approach is to use ASP.NET membership for authentication, link your User class to ASP.NET members, and use your User class for more granular permissions. We do this, because it allows changing authentication providers very easily, while still retaining the ability to have a complex permission system.
另一种方法是使用 ASP.NET 成员身份进行身份验证,将您的 User 类链接到 ASP.NET 成员,并使用您的 User 类获得更细化的权限。我们这样做是因为它允许非常容易地更改身份验证提供者,同时仍然保留拥有复杂权限系统的能力。
In general, it's worth remembering that authentication/identity and storing permissions are not necessarily the same problem.
一般来说,值得记住的是,身份验证/身份和存储权限不一定是同一个问题。
回答by goodguys_activate
You may be interested in RPX for a free API to authenticate your users
您可能对 RPX 感兴趣,以获得免费的 API 来验证您的用户
http://blog.maartenballiauw.be/post/2009/07/27/Authenticating-users-with-RPXNow-(in-ASPNET-MVC).aspx
http://blog.maartenballiauw.be/post/2009/07/27/Authenticating-users-with-RPXNow-(in-ASPNET-MVC).aspx
Try the ASP.Net MVC Membership Starter Kitfor an administrative API
试用管理 API的ASP.Net MVC Membership Starter Kit
Screenshots
截图
http://www.squaredroot.com/2009/08/07/mvcmembership-release-1-0/
http://www.squaredroot.com/2009/08/07/mvcmembership-release-1-0/
Old locations changesets (historic)
旧位置变更集(历史)
http://mvcmembership.codeplex.com/SourceControl/list/changesets
http://mvcmembership.codeplex.com/SourceControl/list/changesets
New Location:
新地点:
回答by AlexC
This is a forth approach. Using the web matrix security classesyou can use simple membership provider which can use EF so users and roles can be part of your domain model but also part of the IPrincipal and IIdentity MVC helpers.
这是第四种方法。使用Web 矩阵安全类,您可以使用简单的成员资格提供程序,它可以使用 EF,因此用户和角色可以成为域模型的一部分,但也可以成为 IPrincipal 和 IIdentity MVC 帮助程序的一部分。
I have created an example Github projectto see how this can be used with automated self registration and email signup / password reset and the like.
我创建了一个示例 Github 项目,以了解如何将其与自动自注册和电子邮件注册/密码重置等一起使用。

