I built this tutorial a while ago. It combines several existing textbooks from several sources .. so maybe you have already seen some of them.
For it to work, you must implement all of the code below in your applications.
Let it begin:
, web.config <system.web>:
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/yourLoginControllerName/YourLoginActionResult" timeout="2880" />
</authentication>
<membership defaultProvider="AccountMembershipProvider">
<providers>
<clear/>
<add name="AccountMembershipProvider"
type="yourProjectName.Web.Infrastructure.AccountMembershipProvider" />
</providers>
</membership>
<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)
{
..
}
. .
, roleManagement , , .
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)
{
}
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(), , - , , , :
[HttpPost]
public ActionResult Login()
{
string user = Request.Params["user"];
if (Membership.ValidateUser(user, Request.Params["password"]))
{
FormsAuthentication.SetAuthCookie(user, true);
return Redirect("/Home/WhereEver");
}
else
return Redirect("/Home/Login");
}
, , .
, .
.