2012-01-23 5 views
1

현재 MVC3 프레임 워크를 사용하여 응용 프로그램을 만들고 있습니다.ASP.NET MVC3 역할

[Authorize(Roles = "Admin")] 

내 질문은 : 나는 역할을 설정하는

내가 좋아하는 필터 역할을 사용하는 방법을 이해? 로그인 중입니까? 어떻게 이루어 집니까?

+0

어떤 멤버쉽 서비스 공급자를 이용하십니까? 기본 제공된 공급자 중 하나를 사용하고 있습니까? 아니면 폼 인증 티켓을 사용하고 있습니까? –

+0

양식 인증 티켓을 사용하고 있습니다. 신청서가 처음부터 만들어져 회원 서비스를 알지 못했습니까? –

답변

6

양식 인증 티켓을 직접 만들 때 일반적으로 티켓의 UserData 부분을 사용하여 사용자와 관련된 정보를 저장합니다. 이것은 역할 일 수 있습니다.

그런 다음 Application_AuthenticateRequest 이벤트의 Global.asax에서 양식 티켓을 구문 분석하고 현재 보안 주체에 역할을 할당합니다. 여기

는 다른 업체와 양식에 대한 몇 가지 가이드에게 인증입니다 : 일반적으로

http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-Forms-Authentication_2C00_-and-Security-Resources-.aspx

에 내가 자주 내 자신의 System.Security.Principal.GenericPrincipal 및 System.Web.Security.FormsIdentity 모든 작업을 수행하기 위해 작성 나를 위해 일해.

public class UserIdentity: System.Web.Security.FormsIdentity 
{ 
    public string[] Roles { get; private set; } 
    public string FirstName { get; private set; } 
    public string UserName { get; private set; } 
    public int UserID { get; private set; } 

    public UserIdentity(System.Web.Security.FormsAuthenticationTicket ticket) : base(ticket) 
    { 
     if (ticket.UserData != null && ticket.UserData.IndexOf("|") != -1) 
     { 
      string[] dataSections = ticket.UserData.Split('|'); 

      //Get the first name 
      FirstName = dataSections.Length >= 3 ? dataSections[2] : ""; 

      //Get the username 
      UserName = ticket.Name; 

      #region Parse the UserID 
      int userID = 0; 
      int.TryParse(dataSections[0], out userID); 
      this.UserID = userID; 
      #endregion 

      this.Roles = System.Text.RegularExpressions.Regex.Split(dataSections[1], ","); 

     } 
    } 
} 

public class UserPrincipal : System.Security.Principal.GenericPrincipal 
{ 
    public UserPrincipal(UserIdentity identity) : base(identity, identity.Roles) 
    { 
    } 
} 

그리고 당신의 Global.asax에서

:

protected void Application_AuthenticateRequest(object sender, EventArgs e) 
    { 
     if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity is System.Web.Security.FormsIdentity) 
     { 

      HttpContext.Current.User = new CAA.Utility.Security.UserPrincipal(HttpContext.Current.User.Identity is CAA.Utility.Security.UserIdentity? HttpContext.Current.User.Identity as CAA.Utility.Security.UserIdentity : new Utility.Security.UserIdentity(((System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity).Ticket));     


     } 
    } 

그리고 티켓 작성 :

   System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(1, user.Username, DateTime.Now, DateTime.Now.AddDays(1), false, String.Format("{0}|{1}|{2}", user.UserID ,user.Roles.ToString(), user.FirstName), System.Web.Security.FormsAuthentication.FormsCookiePath); 
       HttpCookie cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, System.Web.Security.FormsAuthentication.Encrypt(ticket)); 

       if (model.RememberMe) 
        cookie.Expires = ticket.Expiration; 


       Response.Cookies.Add(cookie); 

이 코드는 수행하기 어려울 수 있지만 논리가를 그 사용자 정의 "UserPrincipal "는 Forms Auth 티켓의 UserData 섹션을 자동으로 구문 분석하여 거기에 저장하려는 정보를 자동으로 찾습니다. 내 경우에는 이름, 역할, ID 등을 저장합니다. 내 코드에서 "CAA.Utility.Security"라는 네임 스페이스는 내 사용자 정의 ID 및 사용자를 저장하는 곳입니다.

+0

완벽하고 방금 내가 뭘 찾고 있었습니까! –

2

어디에서 역할을 설정합니까?

이는 web.config에서 어떤 역할 공급자를 사용하는지에 따라 달라집니다.

<roleManager enabled="false"> 
    <providers> 
    <clear/> 
    <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" /> 
    <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /> 
    </providers> 
</roleManager> 

은 당신이 당신의 aspnet_Roles 테이블의 역할을 설정하여 기본 AspNetSqlRoleProvider 공급자를 사용하는 경우. following article을 살펴보십시오. 그러나 사용자 지정 역할 공급자를 사용하는 경우이 공급자가 어떻게 구현되는지에 따라 달라집니다.