所以我有一個登錄頁面,當在通過身份驗證的用戶登錄時,該程序將用戶重定向到如何防止直接URL與登錄頁
Response.Redirect("WebForm1.aspx", false);
但我的問題是,如何阻止用戶只需訪問通過輸入直接URL來登錄受保護的網頁。
所以我有一個登錄頁面,當在通過身份驗證的用戶登錄時,該程序將用戶重定向到如何防止直接URL與登錄頁
Response.Redirect("WebForm1.aspx", false);
但我的問題是,如何阻止用戶只需訪問通過輸入直接URL來登錄受保護的網頁。
以下相應的代碼添加到你的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>
這是執行此操作的「標準」方法。 –
您需要在WebForm1.aspx頁面中有一個函數來檢查以確保用戶已通過身份驗證。例如,在僞代碼 -
def WebForm1(request):
if not user_is_authenticate():
Response.Redirect("LoginPage.aspx", false);
# Display Homepage here
這通常是用含有數據,在此情況下關於用戶的驗證狀態的會話處理。
if(/*user isn't validated*/)//HttpContext.Session[Userisvalidated]==false
Response.Redirect("LoginPage.aspx", false);
的代碼是未經測試,你可以找到更多有關此asp.net sseesion:https://msdn.microsoft.com/en-us/library/ms178581.aspx或在這裏:http://www.w3schools.com/asp/asp_sessions.asp
我從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
你使用的是MVC嗎?或asp.net? – CodingYoshi
我正在使用asp.net – Marvinatorrr