假设我有一个拥有自己的UserAccount,UserRole和其他应用程序所需表的数据库,我想知道如何自定义ASP.Net Identity身份验证以使用我自己创建的数据库表。 ASP.Net Identity首先使用代码,但我不是。我只是想知道我应该怎么做。任何建议都会有所帮助。
提前致谢
答案 0 :(得分:0)
从MembershipProvider和RoleProvider类扩展。实施必要的方法。点配置以使用您的提供商。
非常简单的方法是仅使用角色提供程序:
public class MyRoleProvider : RoleProvider
{
public override bool IsUserInRole(string username, string roleName)
{
throw new NotImplementedException();
}
public override string[] GetRolesForUser(string username)
{
using (var userDao = new UserDao())
{
var user = userDao.GetUser(username);
return user == null ? new string[0] : user.Roles
.Select(r => r.Name).ToArray();
}
}
public override void CreateRole(string roleName)
{
throw new NotImplementedException();
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override string[] GetAllRoles()
{
throw new NotImplementedException();
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotImplementedException();
}
public override string ApplicationName { get; set; }
}
如果它是MVC,那么这是我的 AccountController :
public class AccountsController : Controller
{
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginPage loginPage)
{
if (ModelState.IsValid)
{
using (var userDao = new UserDao())
{
var user = userDao.GetUser(loginPage.Login);
if (user != null && user.Password == loginPage.Password)
{
FormsAuthentication.SetAuthCookie(loginPage.Login, loginPage.RememberMe);
return RedirectToAction("Index", "Campaigns");
}
}
}
return View(loginPage);
}
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login");
}
}
模型(以防万一):
public class LoginPage
{
[Required(ErrorMessage = "Enter login")]
public string Login { get; set; }
[Required(ErrorMessage = "Enter password")]
public string Password { get; set; }
public bool RememberMe { get; set; }
}
配置(内部):
<authentication mode="Forms">
<forms loginUrl="/Accounts/Login" defaultUrl="/Campaigns/Index" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
<roleManager enabled="true" defaultProvider="CustomRoleProvider">
<providers>
<clear />
<add name="CustomRoleProvider" type="BellIntegrator.OsmSkyMobile.Web.Helpers.SkyRoleProvider" />
</providers>
</roleManager>