2009-12-28 205 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