ASP.NET MVC自定义会员资格入门指南

7

我正在创建自己的网站和博客,我希望第一次只有我的名称和密码存储在数据库中,也许以后会有其他人的注册,但首先只有我自己的登录和授权管理。我不想使用MS的Membership。我想从头开始尝试创建自己的Membership,因此我正在寻找初学者指南,但我发现大部分指南都包含角色和权限。我只想要一个小例子,用于检查数据库中的用户名、密码和登录数据。

谢谢您的帮助 Libor


嗨,你已经选择了一种访问数据库的方式吗?(实体框架、linq2sql、ado.net?) - Michel
3个回答

5
即使您不想使用会员和角色提供程序数据存储,仍然可以利用身份验证。相信我,这比构建自己的要容易得多。以下是其工作原理:
假设您已经设置了用户存储以检索用户名和密码。为简单起见,我将假装您拥有一个名为DataLayer的静态类,其中包含从数据库(或其他存储)中提取信息的数据检索方法。
首先,您需要一种让用户登录的方法。因此,请设置具有用户名和密码字段的页面。然后,在该页面提交到的操作方法中设置一个快速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();


1

嘿 @Bibo,很好没有选择Membership提供程序。我认为一个UserService或类似的服务应该足够提供创建、验证用户和一些其他方法。作为建议,请使用密码哈希和用户密码的密码盐。这是一个不错的链接在这里。还可以看看我以前给出的这个答案

祝你好运!

编辑:rememberMe参数应该被命名为keepMeSignedIn。


谢谢回答,但我找不到任何有用的东西。你能链接一些相关文章吗? - Libor Zapletal
1
CodeCampServer是一个示例应用程序,实现了您正在寻找的内容。 - uvita

1

这篇关于表单身份验证的文章为您提供了大量信息,以创建自己的简单安全系统,尤其是关于FormsAuthenticationTicket的部分。

http://support.microsoft.com/kb/301240


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接