繁体   English   中英

禁止用户无需登录即可访问页面/ URL

[英]Disallow a user to visit a page/URL without Logged In

我是ASP.net的新手,是新手,但我正在自己学习它! 我正在测试和学习ASP.NET中的登录和注销功能。 实际上,我的问题是我有一个简单的页面,即用于登录目的的Default.aspx为:

<body>
<form id="form1" runat="server">
<div>
    <h1>Please Sign in</h1>
    UserName:
    <asp:TextBox id="uname"  runat="server"></asp:TextBox>
    <br/>
    Password:
    <asp:TextBox id="upass"  runat="server"></asp:TextBox>
    <br/>
    <asp:Button id="but"  runat="server" text="signup" OnClick="but_Click"/>
    <br/>
    <asp:Label ID ="lblInformation" runat ="server" ForeColor ="Red"/>
</div>
</form>
</body>

我以(Default.aspx.cs)身份登录:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    String name = null;
    String pass = null;

    protected void but_Click(object sender, EventArgs e)
    {
        name = uname.Text;
        pass = upass.Text;
        if (name.Equals("admin")&&pass.Equals("admin"))
        {
            FormsAuthentication.RedirectFromLoginPage(name, false );
        }
    }
}

成功登录后; 重定向到Home.aspx为:

 <body>
   <form id="form1" runat="server">
     <div>
       <h1>Hello User</h1>
        <asp:Button ID="but" OnClick="but_Click" text="signout" runat="server"/>
     </div>
   </form>
 </body>

我以Home.aspx.cs的身份注销

 public partial class Home : System.Web.UI.Page
 {
   protected void Page_Load(object sender, EventArgs e)
   {
   }
   protected void but_Click(object sender, EventArgs e)
   {
      FormsAuthentication.SignOut();
      FormsAuthentication.RedirectToLoginPage();
   }
 }

问题问题是登录后,如果我复制Home.aspx页面URL(登录后我登陆的页面),然后粘贴到浏览器搜索栏中并按Enter,就可以看到它,而无需登录!

我的意思是我希望我的用户在任何情况下都没有登录时限制登陆Home.aspx!

所以问题是,如果我的用户尚未登录,我如何才能限制其查看Home.aspx页面,因为即使我没有登录也可以通过将Home.aspx URl复制到浏览器中来查看该页面!

对不起,我的英语不是我来自英国的国家,而是我自己学习asp.net。

谢谢

Page_Load事件中检查授权。

if (!User.Identity.IsAuthenticated)
{
    Response.Redirect("~/Login.aspx");
}

可能最简单的方法是在Home.aspx的Page_Load方法中,添加

if(!Request.IsAuthenticated) { FormsAuthentication.RedirectToLogin(); }

让ASP.Net为您完成工作; 您可以通过web.config进行控制。

您可以将以下内容添加到<system.web>部分:

  <!-- Specify that only authenticated users are allowed to access pages by default. 
   Those that anonymous users can access will be specified separately. -->
  <authorization>
    <deny users="?" />
  </authorization>

然后,您可以添加以下条目,以允许未登录的用户访问default.aspx:

<!-- Specify those files that all users can access, even if they aren't logged in -->
<location path="Default.aspx">
  <system.web>
    <authorization>
      <allow users="*" />
    </authorization>
  </system.web>
</location>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM