2016-12-14 37 views
0

所以我有一個登錄頁面,當在通過身份驗證的用戶登錄時,該程序將用戶重定向到如何防止直接URL與登錄頁

Response.Redirect("WebForm1.aspx", false); 

但我的問題是,如何阻止用戶只需訪問通過輸入直接URL來登錄受保護的網頁。

+0

你使用的是MVC嗎?或asp.net? – CodingYoshi

+0

我正在使用asp.net – Marvinatorrr

回答

1

以下相應的代碼添加到你的web.config。如果您的web.config中已經有system.web。確保你只複製裏面的內容。因爲你的網絡配置中不能有多個system.web。如果你想允許用戶訪問另一個頁面而無需登錄。您可以根據需要添加其他位置路徑作爲Login.aspx。

<configuration> 
    <location path="~/Account/Login.aspx"> 
     <system.web> 
      <authorization> 
       <allow users="?" /> 
      </authorization> 
     </system.web> 
    </location> 
    <system.web> 
     <authentication mode="Forms"> 
      <forms loginUrl="~/Account/Login.aspx" timeout="2880"/> 
     </authentication> 
     <authorization> 
      <deny users="?"/> 
     </authorization> 
    </system.web> 
</configuration> 
+0

這是執行此操作的「標準」方法。 –

0

您需要在WebForm1.aspx頁面中有一個函數來檢查以確保用戶已通過身份驗證。例如,在僞代碼 -

def WebForm1(request): 

    if not user_is_authenticate(): 
     Response.Redirect("LoginPage.aspx", false); 

    # Display Homepage here 
0

我從here複製這個,如果你想了解更多。您應該

生成身份驗證票據,對其進行加密,創建cookie,將其添加到響應中,並在[成功登錄後]重定向用戶。這使您可以更好地控制如何創建Cookie。在這種情況下,您還可以包含自定義數據以及FormsAuthenticationTicket。

下面是一些代碼:

if (ValidateUser(txtUserName.Value,txtUserPass.Value)) 
    { 
     FormsAuthenticationTicket tkt; 
     string cookiestr; 
     HttpCookie ck; 
     tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now, 
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data"); 
     cookiestr = FormsAuthentication.Encrypt(tkt); 
     ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr); 
     if (chkPersistCookie.Checked) 
     ck.Expires=tkt.Expiration;  
      ck.Path = FormsAuthentication.FormsCookiePath; 
     Response.Cookies.Add(ck); 

     string strRedirect; 
     strRedirect = Request["ReturnUrl"]; 
     if (strRedirect==null) 
      strRedirect = "default.aspx"; 
     Response.Redirect(strRedirect, true); 
    } 
    else 
     Response.Redirect("logon.aspx", true); 

這裏是另一種方式來檢查,如果用戶進行身份驗證:

bool isAuthenticated = System.Web.HttpContext.Current.User.Identity.IsAuthenticated 
相關問題