我不久前建立了这个教程..
它结合了来自几个来源的一些现有教程。所以,也许你已经看过其中的一部分了。
为了让它工作,您必须在您的应用程序中实现以下所有代码。
让我们开始吧:
当您的应用程序 web.config 文件在<system.web> 标记下具有以下部分时,将激活数据注释机制:
<system.web>
<!-- authentication section activates the auth system -->
<authentication mode="Forms">
<forms loginUrl="~/yourLoginControllerName/YourLoginActionResult" timeout="2880" />
</authentication>
<!-- membership section defines which class is used to check authentication, in this example, this is the default class -->
<membership defaultProvider="AccountMembershipProvider">
<providers>
<clear/>
<add name="AccountMembershipProvider"
type="yourProjectName.Web.Infrastructure.AccountMembershipProvider" />
</providers>
</membership>
<!-- roleManager section defines which class is used to check roles for users, in this example, the default class is used -->
<roleManager enabled="true" defaultProvider="AccountRoleProvider">
<providers>
<clear/>
<add name="AccountRoleProvider"
type="yourProjectName.Web.Infrastructure.AccountRoleProvider" />
</providers>
</roleManager>
..
</system.web>
装饰允许您控制哪些角色可以访问哪些控制器操作,并定义控制器操作是需要身份验证才能访问它们还是可以被所有用户访问。控制是通过控制器中的以下属性来完成的,例如:
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
..
}
[Authorize(Roles = "Administrator, KingOnRails")]
public ActionResult Edit(int Id)
{
..
}
默认系统限制您按原样使用数据注释。它需要数据库连接来创建用户表和角色。
下面将向您展示如何覆盖它并将成员资格和角色管理类替换为简单的类,这些类可以使用您自己的 3rd 方库对用户进行身份验证并赋予他们角色。
您需要实现以下 2 个类,为了更好的可读性,请将它们放在解决方案中的同一文件夹中:
public class AccountMembershipProvider : MembershipProvider
{
public override bool ValidateUser(string username, string password)
{
if (username == "KingOnRails")
return true;
return false;
}
}
还有:
public class AccountRoleProvider : RoleProvider
{
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
//Here you can implement insertion of <key, value> = <user, role> to a global dictionary maintained in Global.asax file...
}
public override string[] GetRolesForUser(string username)
{
if (username == "Roy Doron")
return new string[1] { "User" };
else if (username == "KingOnRails")
return new string[1] { "Administrator" };
return null;
}
public override bool RoleExists(string roleName)
{
if ((roleName == "Administrator") || (roleName == "User"))
return true;
else
return false;
}
}
就是这样.. 现在您只需在登录控制器中编写自己的流程(如果有),如果没有,则需要实现一个登录页面。
当用户尝试登录到您的系统时,登录控制器应调用成员资格 ValidateUser() 方法,如果成功,则需要为该用户创建 Web 表单身份验证票,然后将用户重定向到您想要的任何位置,例如:
[HttpPost]
public ActionResult Login()
{
string user = Request.Params["user"];
// calls the AccountMembershipProvider.ValidateUser()
if (Membership.ValidateUser(user, Request.Params["password"]))
{
FormsAuthentication.SetAuthCookie(user, true);
return Redirect("/Home/WhereEver");
}
else
return Redirect("/Home/Login");
}
就是这样,希望对你有帮助。
如果您有任何其他问题,请随时提出。
祝你好运。