如何使用登录页面阻止直接URL

时间:2016-12-14 00:59:10

标签: asp.net login

所以我有一个登录页面,当经过身份验证的用户登录时,程序会将用户重定向到

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

但我的问题是如何通过输入直接网址来阻止用户只是访问登录保护的网页。

4 个答案:

答案 0 :(得分:1)

相应地将以下代码添加到web.config中。如果你的web.config中已有system.web。确保你只复制内部。因为您的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>

答案 1 :(得分:0)

您需要在WebForm1.aspx页面中有一个函数来检查以确保用户已通过身份验证。例如,在伪代码中 -

def WebForm1(request):

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

    # Display Homepage here

答案 2 :(得分:0)

这通常由包含数据的会话处理,在本例中是关于用户的验证状态。

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

答案 3 :(得分: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