2009-12-28 5 views
4
내 모든 문제를 해결 한 사용자 정의 사용자 인증하지만 아무도 관한 여기에 많은 게시물을 검색 한

ASP.NET MVC 및 로그인 인증

내가 ASP.NET MVC에 새로운 오전과 기존의 ASP.NET (웹폼)를 사용했다 그러나 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/MvcMembership을 읽어보십시오 –

+0

Jay Zeng과 강력하게 동의합니다. 회원 자격을 (잘못) 개혁하지 마십시오 : http://blogs.teamb.com/craigstuntz/2009/09/09/38390/ –

+0

글쎄, 내가 원하는대로 맞춤 설정할 수 있습니까? 왜냐하면 필자는 HELP DESK 응용 프로그램을 개발하려고하고 관리자 만이 사용자를 만들 수 있기 때문에 등록이 공개가 아니기 때문에 내 사용자 테이블과 역할 테이블이 다릅니다. 이 방법으로 사용자 정의 할 수 있습니까? – user239684

답변

6

자습서에 대한 의견이 있으시면 학습 section on security을 참조하십시오.

특히 this 로그인하여 안전한 ASP.NET MVC 5 웹 응용 프로그램 만들기, 이메일 확인 및 비밀번호 재설정에 대한 자습서입니다.

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

나에게 효과가 없다 .. 해결하도록 도와주세요. 집으로 리디렉션하지만 다시 로그인으로 리디렉션되기 때문에 인증이 작동하지 않는다고 생각합니다. 어떻게 해결할 수 있을까요? –

+0

@DatzMe 브라우저의 쿠키를보고 인증이 설정되었는지 확인하십시오. –

+0

그래, 친구 야. 내 web.config에 문제가있는 것 같아. –

0

코드 :

using Microsoft.AspNet.Identity; 


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

자세한 정보로 편집하십시오. 코드 전용 및 "시도하십시오"답변은 검색 가능한 콘텐츠가 없으므로 권장하지 않으며 누군가가 "시도해"야하는 이유를 설명하지 않습니다. 우리는 여기서 지식을위한 자원이되기 위해 노력합니다. – abarisone