我正在创建自己的网站和博客,我希望第一次只有我自己在数据库中(我的姓名和密码),然后可能会为其他人注册一些,但首先只为我登录并获得授权管理。我不想使用 MS 的会员资格。我想尝试从一开始就创建自己的,所以我正在寻找初学者指南,但我找到了具有角色和权利的大型指南。我只想用登录数据检查数据库中的用户名、密码的小例子。感谢帮助
3 回答
即使您不想使用成员资格和角色提供者数据存储,您仍然可以使用身份验证。相信我,这比构建自己的要容易得多。以下是它的工作原理:
我们会说您已经设置了用于检索用户名和密码的用户存储设置。为了简单起见,我将假设您有一个名为 DataLayer 的静态类,其中包含用于从数据库(或您使用的任何存储)中提取信息的数据检索方法。
首先,您需要一种让用户登录的方法。因此,请设置一个包含用户名和密码字段的页面。然后在页面发布的action方法中设置一个快速的if语句:
if (DataLayer.UserExists(userModel.Username))
{
User userFromDB = DataLayer.GetUser(userModel.Username);
if (userFromDB.Password == userModel.Password)
{
FormsAuthentication.SetAuthCookie(userFromDB.Username, checkBoxRememberMe.Checked);
//Use userFromDB as the username to authenticate because it will
//preserve capitalization of their username the way they entered it
//into the database; that way, if they registered as "Bob" but they
//type in "bob" in the login field, they will still be authenticated
//as "Bob" so their comments on your blogs will show their name
//the way they intended it to.
return "Successfully logged in!";
}
}
return "Invalid username or password.";
现在他们已通过身份验证,您可以在代码中使用 Page.User.Identity.IsAuthenticated 来确定他们是否已登录。像这样:
if (User.Identity.IsAuthenticated)
{
DataLayer.PostBlogComment(User.Identity.Name, commentBody);
//Then in your controller that renders blog comments you would obviously
//have some logic to get the user from storage by the username, then pull
//their avatar and any other useful information to display along side the
//blog comment. This is just an example.
}
此外,您可以将整个操作方法甚至整个控制器锁定给通过表单身份验证提供程序进行身份验证的用户。您所要做的就是将这些标签添加到您的操作方法/控制器中:
[Authorize]
public ActionResult SomeActionMethod()
{
return View();
}
该[Authorize]
属性将阻止未登录的用户访问该操作方法,并将他们重定向到您的登录页面。如果您使用内置角色提供程序,则可以使用相同的属性来过滤掉角色。
[Authorize(Roles="Admin, SalesReps")]
public ActionResult SomeActionMethod()
{
return View();
}
这些属性也可以添加到控制器类之上,以将其逻辑应用于整个控制器。
编辑:要注销用户,您需要做的就是调用FormsAuthentication.SignOut();
这篇关于表单身份验证的文章为您提供了创建自己的简单安全系统的大量信息,尤其是有关 FormsAuthenticationTicket 的部分。