禁止用户在未登录的情况下访问页面/URL
本文关键字:访问 URL 情况下 用户 登录 禁止 | 更新日期: 2023-09-27 18:10:13
我是ASP.net的新手,但是我正在自己学习!我正在测试和学习在ASP.NET中登录和注销功能。实际上我的问题是,我有一个简单的页面,即默认。用于登录的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(我登录后登陆的页面),粘贴在浏览器搜索栏中,按回车键,我就能看到它了,而不是我已经登录了!
我的意思是我希望我的用户限制登陆在主页。Aspx如果他没有在任何情况下登录!
问题是我如何限制我的用户查看主页。aspx页,如果他没有登录,因为我可以查看页面,即使我没有登录只是通过复制主页。aspx URl到浏览器!
对不起,我的英语不好,我不是来自英语国家,我只是在学习自己的asp.net。
谢谢
在Page_Load
事件检查授权
if (!User.Identity.IsAuthenticated)
{
Response.Redirect("~/Login.aspx");
}
可能最简单的方法是在Home中。aspx的Page_Load方法,添加
if(!Request.IsAuthenticated) { FormsAuthentication.RedirectToLogin(); }
我替你做事;你可以通过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>