2009-01-25 43 views
6

我正在與asp.net網站項目合作,一些頁面需要驗證。我正在使用asp.net成員資格。什麼是使asp.net中的某些頁面需要登錄的最佳方式?

我看了一些答案。例如在文件夾中創建所有這些頁面並創建描述該特權的內部web.config。這是解決問題的一種方式,但我需要更加可修復和有效的方式。

+0

你是什麼意思「更可修復和有效」?上面列出的方法有什麼問題? – 2009-01-25 12:13:32

回答

20

如果您不想在web.config中對此進行硬編碼,則需要實現「基頁」類型的控件。

您的基頁類應該繼承System.Web.UI.Page,並且需要有一個方法可以調用說「用戶必須登錄」或「用戶必須在角色x中」,並且if用戶不在該角色中,重定向到登錄頁面(您可以通過調用FormsAuthentication.LoginUrl來獲取此內容)。

您的實際頁面應該繼承此類,而不是直接從System.Web.UI.Page繼承。然後,像初始化,或者在Page_Load中的頂部,叫

base.UserMustBeLoggedIn(); 

// Replace "AccessRole" with the name of your role 
base.UserMustBeInRole("AccessRole"); 

而讓基頁處理這個問題。

如果您希望將訪問權限存儲在數據庫中,那麼您可以將所有處理移動到基本頁面,並在頁面生命週期的適當位置,根據數據庫表格檢查當前URL,檢查用戶根據需求進行角色/身份驗證,並根據需要重定向。


注意,您可以在Web配置頁面創建安全級別,像這樣:

<configuration> 
    <location path="LockedPage.aspx"> 
    <system.web> 
     <authorization> 
     <!-- Deny access to anonymous users --> 
     <deny users="?"/> 
     </authorization> 
    </system.web> 
    </location> 
</configuration> 

更多信息,請訪問MSDN:The Location ElementThe Authorization Element

3

你可以試試這個代碼, 在母版頁加載事件編寫此代碼, 添加屬性

公共BOOL m_bLoginRequired = TRUE;

public bool IsLoginRequired 
{ 
    get { return m_bLoginRequired; } 
    set { m_bLoginRequired = value; } 
} 



try 
     { 
      // Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache); 
      Response.Cache.SetNoStore(); 
      if (IsLoginRequired==true) 
      { 
        if (Session.IsNewSession || HttpContext.Current.Session["Username"] == null) 
        { 
         FormsAuthentication.SignOut(); 
         FormsAuthentication.RedirectToLoginPage("Session Expired"); 
         Response.End(); 
        } 
       } 
      } 
     catch (Exception ex) 
     { 
      throw (ex); 
     } 

現在登錄頁面,你需要編寫代碼

FormsAuthentication.SetAuthCookie(this.txt_UserName.Text.Trim(), false); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, this.txt_UserName.Text.Trim(), DateTime.Now, DateTime.Now.AddMinutes(10), false, "HR"); 
      HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); 
      cookie.Name = "jay"; 
      Session["UserName"] = txt_UserName.Text.Trim(); 
      Response.Cookies.Add(cookie); 
      txt_UserName.Text = ""; 
      txt_Password.Text = ""; 
      Response.Redirect("HomePage2.aspx"); 

現在你AVE在登錄頁面

protected void Page_PreInit(object sender, EventArgs e) 
    { 
     Master.IsLoginRequired = false; 
    } 

添加pageinit事件,如果你想用戶可以訪問一個未經授權的頁面,然後在該頁面的pageinit事件中使用

設置Master.IsLoginRequired=false;

還指定web.config文件中的登錄名。

相關問題