2013-07-29 224 views
2

我正在爲我的管理頁面進行身份驗證。我遵循各種網站的示例,但每次嘗試訪問產品頁面時,它總是會踢我回到登錄頁面。角色身份驗證和授權

這是我的代碼

login.aspx.cs

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
     if (User.Identity.IsAuthenticated && Request.QueryString["ReturnUrl"] != "") 
     { 
      divError.Visible = true; 
      divError.InnerHtml = accessErrorMessage; 
     } 
    } 
} 

protected void btn_enter_Click(object sender, EventArgs e) 
{ 
    using (var db = new MainDB()) 
    { 
     administrator=db.Administrators.Where(q => q.Name == txtUsername.Text && q.Password == txtPassword.Text).FirstOrDefault(); 

     if(administrator!=null) 
     { 
      administrator.DateLastLogin = DateTime.Now; 
      roles = administrator.Role; 
      adminID = administrator.AdministratorId; 
      db.SaveChanges(); 

      FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
       1, // Ticket version 
       adminID.ToString(),      // Username associated with ticket 
       DateTime.UtcNow,      // Date/time issued 
       DateTime.UtcNow.AddMinutes(30),   // Date/time to expire 
       true,         // "true" for a persistent user cookie    
       **roles,  // User-data, in this case the roles(data example: product,feedback,subscribes** 
       FormsAuthentication.FormsCookiePath); // Path cookie valid for 

      // Encrypt the cookie using the machine key for secure transport 
      string hash = FormsAuthentication.Encrypt(ticket); 
      HttpCookie cookie = new HttpCookie(
       FormsAuthentication.FormsCookieName, // Name of authentication cookie 
       hash); // Hashed ticket 

      // Set the cookie's expiration time to the tickets expiration time 
      if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; 

      // Add the cookie to the list for outgoing response 
      Response.Cookies.Add(cookie); 

      // Redirect to requested URL, or homepage if no previous page 
      // requested 
      string returnUrl = Request.QueryString["ReturnUrl"]; 
      if (returnUrl == null) 
      { 
       returnUrl = "~/admin/"; 
      } 
      // Don't call FormsAuthentication.RedirectFromLoginPage since it 
      // could 
      // replace the authentication ticket (cookie) we just added 
      Response.Redirect(returnUrl); 
     } 
     else 
     { 
      divError.Visible = true; 
      divError.InnerHtml = loginErrorMessage; 
     } 
     //if (FormsAuthentication.Authenticate(txtUsername.Text, txtPassword.Text)) 
      //{ 
      // FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, false); 
      //}  
    } 

Global.asax的

void Application_AuthenticateRequest(object sender, EventArgs e) 
{ 
    if(Request.IsAuthenticated) 
    { 
     FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity; 

     //Add the roles to the User Principal 
     HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(HttpContext.Current.User.Identity, identity.Ticket.UserData.Split(new char[] { ',' })); 
    } 
} 

的web.config

<location path="admin/product"> 
<system.web> 
    <authorization> 
    <!--<allow users="admin"/>--> 
    <allow roles="product"/> 
    <deny users="*"/> 
    </authorization> 
</system.web> 

<location path="admin/spotlight"> 
<system.web> 
    <authorization> 
    <!--<allow users="admin"/>--> 
    <allow roles="spotlight"/> 
    <deny users="*"/> 
    </authorization> 
</system.web> 

<location path="admin/career"> 
<system.web> 
    <authorization> 
    <!--<allow users="admin"/>--> 
    <allow roles="career"/> 
    <deny users="*"/> 
    </authorization> 
</system.web> 

<location path="admin/emailshare"> 
<system.web> 
    <authorization> 
    <!--<allow users="admin"/>--> 
    <allow roles="emailshare"/> 
    <deny users="*"/> 
    </authorization> 
</system.web> 

我在這裏幹什麼什麼了嗎?

+0

是誰正在嘗試訪問產品頁面的身份驗證用戶,任何角色的一部分? –

+0

@FlopScientist是的...在「角色」字段中有多個值...例如:產品,反饋,訂閱者, 每個人都用逗號分開 –

+0

好的。那麼你確定Authenticated用戶是角色:產品?至少有你一直在嘗試的用戶憑據,它總是會將你發送到登錄頁面? –

回答

1

您首先允許角色,但是拒絕所有用戶。

規則是按順序執行的,所以儘量指定最具體的規則作爲最後一條規則。

<deny users="*"/> 
<allow roles="emailshare"/> 

另一件事,你是從數據庫認證用戶後沒有設置校長。您需要在HttpContext中設置用戶,並且標記爲Authenticated。否則,如果(Request.IsAuthenticated)將始終是錯誤的。

GenericIdentity userIdentity = 
    new GenericIdentity(ticket.Name); 
GenericPrincipal userPrincipal = 
    new GenericPrincipal(userIdentity, roles); 
Context.User = userPrincipal; 

請注意,roles參數是逗號分隔的字符串。

此外,使用build-in provider model會不會更容易?這可以防止你自己編寫所有的驗證代碼。您可以在需要時使用您自己的數據訪問邏輯創建您的custom Membership provider

+0

感謝您的迅速回復...我做了像你提到的變化,但它仍然踢我回到登錄頁面。 對不起,因爲我是新手,我的老闆給了我一個例子,並要求我遵循這個方法。這就是爲什麼我訴諸此.. –

+0

我更新了我的答案。我認爲在驗證用戶身份之後,您可能還需要設置IIdentity。 – Ronald