2009-12-28 158 views
4

我已搜查这里很多帖子关于自定义用户身份验证,但没有已经解决了我所有的顾虑ASP.NET MVC和登录认证

我新的ASP.NET MVC,并使用传统的ASP.NET(Web窗体)但不知道如何为使用ASP.NET MVC的用户构建登录/身份验证机制。

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) 
{ 
    string userName = Login1.UserName; 
    string password = Login1.Password; 
    bool rememberUserName = Login1.RememberMeSet; 

    if (validateuser(userName, password)) 
    { 
     //Fetch the role 
     Database db = DatabaseFactory.CreateDatabase(); 


     //Create Command object 
     System.Data.Common.DbCommand cmd = db.GetStoredProcCommand("sp_RolesForUser"); 
     db.AddInParameter(cmd, "@Uid", System.Data.DbType.String, 15); 
     db.SetParameterValue(cmd, "@Uid", Login1.UserName); 
     System.Data.IDataReader reader = db.ExecuteReader(cmd); 
     System.Collections.ArrayList roleList = new System.Collections.ArrayList(); 
     if (reader.Read()) 
     { 
      roleList.Add(reader[0]); 
      string myRoles = (string)roleList[0]; 

      //Create Form Authentication ticket 
      //Parameter(1) = Ticket version 
      //Parameter(2) = User ID 
      //Parameter(3) = Ticket Current Date and Time 
      //Parameter(4) = Ticket Expiry 
      //Parameter(5) = Remember me check 
      //Parameter(6) = User Associated Roles in this ticket 
      //Parameter(7) = Cookie Path (if any) 
      FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, 
      DateTime.Now.AddMinutes(20), rememberUserName, myRoles, FormsAuthentication.FormsCookiePath); 

      //For security reasons we may hash the cookies 
      string hashCookies = FormsAuthentication.Encrypt(ticket); 
      HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies); 

      // add the cookie to user browser 
      Response.Cookies.Add(cookie); 

      if (HttpContext.Current.User.IsInRole("Administrators")) 
      { 
       Response.Redirect("~/Admin/Default.aspx"); 
      } 
      else 
      { 
       string returnURL = "~/Default.aspx"; 

       // get the requested page 
       //string returnUrl = Request.QueryString["ReturnUrl"]; 
       //if (returnUrl == null) 
       // returnUrl = "~/Default.aspx"; 
       Response.Redirect(returnURL); 
      } 
     } 
    } 
} 

    protected bool validateuser(string UserName, string Password) 
    { 
    Boolean boolReturnValue = false; 

    //Create Connection using Enterprise Library Database Factory 
    Database db = DatabaseFactory.CreateDatabase(); 

    //Create Command object 
    DbCommand cmd = db.GetStoredProcCommand("sp_ValidateUser"); 

    db.AddInParameter(cmd, "@userid", DbType.String, 15); 
    db.SetParameterValue(cmd, "@userid", Login1.UserName); 

    db.AddInParameter(cmd, "@password", DbType.String, 15); 
    db.SetParameterValue(cmd, "@password", Login1.Password); 

    db.AddOutParameter(cmd, "@retval", DbType.Int16, 2); 
    db.ExecuteNonQuery(cmd); 

    int theStatus = (System.Int16)db.GetParameterValue(cmd, "@retval"); 

    if (theStatus > 0) //Authenticated user 
     boolReturnValue = true; 
    else //UnAuthorized... 
     boolReturnValue = false; 

    return boolReturnValue; 
} 

我真的不知道如何将该ASP.NET代码翻译成MVC-esque体系结构;而且我仍然对如何在ASP.NET MVC中实现身份验证感到茫然。

我需要做什么?我如何在ASP.NET MVC中实现上述代码?那些代码中缺少什么?

+4

ASPNET MVC附带了一个完全成熟的成员组成,哪些功能是烂摊子?您可以阅读http://www.codeplex.com/McCMembership开始 – 2009-12-28 17:54:30

+0

非常赞同Jay Zeng。不要(错误地)重新创建成员资格:http://blogs.teamb.com/craigstuntz/2009/09/09/38390/ – 2009-12-28 17:59:35

+0

那么它可以像我想要的那样定制?因为我的用户表和角色表是不同的,因为我打算开发一个HELP DESK应用程序,并且注册不是针对公众的,因为只有管理员可以创建用户。我可以自定义这种方式吗? – user239684 2009-12-28 18:36:27

回答

6

鉴于您对教程的评论,请参阅学习section on security

特别是,this关于通过登录,电子邮件确认和密码重置创建安全的ASP.NET MVC 5 Web应用程序的教程。

22

您可以自己编写验证服务。 这里有一个小故事:

您的用户模型类(即)

public class User 
    { 
     public int UserId { get; set; } 
     public string Name { get; set; } 
     public string Username { get; set; } 
     public string Password { get; set; } 
     public string Email { get; set; } 
     public bool IsAdmin { get; set; } 
    } 

你的用户信息库类(即)

public class UserRepository 
    { 
     Context context = new Context();  
     public User GetByUsernameAndPassword(User user) 
     { 
      return context.Users.Where(u => u.Username==user.Username & u.Password==user.Password).FirstOrDefault(); 
     } 
    } 

和用户应用程序类(即)

public class UserApplication 
    { 
     UserRepository userRepo = new UserRepository();  
     public User GetByUsernameAndPassword(User user) 
     { 
      return userRepo.GetByUsernameAndPassword(user); 
     } 
    } 

这是您的帐户控制器(即)

public class AccountController : Controller 
    { 
     UserApplication userApp = new UserApplication(); 
     SessionContext context = new SessionContext(); 

     public ActionResult Login() 
     { 
      return View(); 
     } 
     [HttpPost] 
     public ActionResult Login(User user) 
     { 
      var authenticatedUser = userApp.GetByUsernameAndPassword(user); 
      if (authenticatedUser != null) 
      { 
       context.SetAuthenticationToken(authenticatedUser.UserId.ToString(),false, authenticatedUser); 
       return RedirectToAction("Index", "Home"); 
      } 

      return View(); 
     } 

     public ActionResult Logout() 
     { 
      FormsAuthentication.SignOut(); 
      return RedirectToAction("Index", "Home"); 
     } 

而且你SessionContext类(即)

public class SessionContext 
    { 
     public void SetAuthenticationToken(string name, bool isPersistant, User userData) 
     { 
      string data = null; 
      if (userData != null) 
       data = new JavaScriptSerializer().Serialize(userData); 

      FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, name, DateTime.Now, DateTime.Now.AddYears(1), isPersistant, userData.UserId.ToString()); 

      string cookieData = FormsAuthentication.Encrypt(ticket); 
      HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieData) 
      { 
       HttpOnly = true, 
       Expires = ticket.Expiration 
      }; 

      HttpContext.Current.Response.Cookies.Add(cookie); 
     } 

     public User GetUserData() 
     { 
      User userData = null; 

      try 
      { 
       HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; 
       if (cookie != null) 
       { 
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); 

        userData = new JavaScriptSerializer().Deserialize(ticket.UserData, typeof(User)) as User; 
       } 
      } 
      catch (Exception ex) 
      { 
      } 

      return userData; 
     } 
    } 

最后下列标记添加到您的标记在web.config文件:

<authentication mode="Forms"> 
    <forms loginUrl="~/Account/Login" timeout="2880" /> 
</authentication> 

而现在你只需要插入[在每个需要验证的控制器的头部设置[Autorize]属性。如下所示:

[Authorize] 
public class ClassController : Controller 
{ 
    ... 
} 
+0

不适合我..请帮我解决它。它重定向到家中,但我认为身份验证不起作用,因为它再次重定向到登录。如何解决这个问题? – 2015-05-13 10:19:01

+0

@DatzMe看看你的浏览器的cookie,看看是否设置了身份验证。 – 2015-05-17 07:41:02

+0

是的,我得到了队友..我在我的web.config中找到了问题 – 2015-05-18 05:15:32

0

代码:

using Microsoft.AspNet.Identity; 


if (Request.IsAuthenticated) 
     { 
      return View(); 
     } 
+7

请编辑更多的信息。仅限代码和“尝试这个”的答案是不鼓励的,因为它们不包含可搜索的内容,也不解释为什么有人应该“尝试这个”。我们在这里努力成为知识的资源。 – abarisone 2016-06-22 11:59:13