问题描述
我正在学习ASP.NET MVC,以前从未使用过.Net授权和成员资格工具.
I am learning ASP.NET MVC and I have never worked with the .Net Authorisation, and Membership tool before.
我正在创建一个应用程序,该应用程序将允许用户登录和他们拥有的动物,因此它将具有许多表
I am creating an application that will let users log in and animals they own so it will have a number of tables
在教程中,我研究了成员资格和授权工具,它似乎为登录数据创建了一个新数据库.这将如何与我自己的自定义表一起使用?
In tutorials I have looked at the membership and authorisation tool seems to create a new database for the login data. How would this work with my own custom tables?
谢谢
推荐答案
如果您有自定义表格,这确实很容易做到.但是在这种情况下,您必须手动检查密码.
It's really easy to do, if you have custom tables. But in this case you have to check the password manually.
这里有几个简单的步骤.
Here are few simple steps.
首先,将表单授权添加到您的web.config文件中:
First, add forms authorization to your web.config file:
<authentication mode="Forms">
<forms loginUrl="~/login" defaultUrl="/" name=".ASPXFORMSAUTH" protection="All" slidingExpiration="true" path="/" timeout="50000000" />
</authentication>
确保已在RouteConfig.cs中正确配置了控制器
Make sure you have controller properly configured in RouteConfig.cs
routes.MapRoute("Login", "login", new { controller = "Login", action = "Login" });
根据存储在现有表中的信息,设置您自己的密码验证功能:
Make your own password validation function, based on information stored in your existing tables:
public bool ValidatePassword(string email, string password)
{
bool isValid = false;
// TODO: put your validation logic here
return isValid;
}
请注意,您可以使用用户名或电子邮件.我更喜欢电子邮件,因为用户永远不会忘记他们的电子邮件,但是经常会有多个用户名.
Note that you can use username or email. I prefer email, because users never forget their emails, but often have several usernames.
创建您的登录控制器:
public class LoginController : Controller
{
[HttpGet]
public ActionResult Login()
{
if(Request.IsAuthenticated)
{
return View("AlreadyLoggedIn");
}
return View();
}
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel viewModel)
{
if(ModelState.IsValid)
{
var isPasswordValid = ValidatePassword(viewModel.Email, viewModel.Password);
if(isPasswordValid)
{
FormsAuthentication.SetAuthCookie(viewModel.Email, true);
// now the user is authenticated
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("password", "Invalid password");
}
}
return View(viewModel);
}
}
视图模型非常简单:
public class LoginViewModel
{
[Required(ErrorMessage = "Please type your email")]
[EmailAddress(ErrorMessage = "Please provide correct email address")]
public string Email { get; set; }
[Required(ErrorMessage = "Please type your password")]
public string Password { get; set; }
}
如果您想限制对某些页面的访问,请使用Authorize属性:
And if you want to restrict access to some of your pages, use Authorize attribute:
public class AnotherController : Controller
{
[Authorize, HttpGet]
public ActionResult Index()
{
...
}
}
总而言之,您只需要将所有数据库登录验证逻辑放在ValidatePassword函数中即可!
To summarize, you just need to put all your database login verification logic to ValidatePassword function, and that's it!
这篇关于具有ASP.NET成员资格和授权的自定义数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!