Here is my web.config
:
<system.web>
<compilation debug="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.8" />
<pages>
<namespaces>
<add namespace="System.Web.Optimization" />
</namespaces>
<controls>
<add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
</controls>
</pages>
<caching>
</caching>
<authentication mode="Forms">
<forms loginUrl="logon.aspx" defaultUrl="Default.aspx" />
</authentication>
<authorization>
<deny users="*"/>
</authorization>
</system.web>
The expected output is that logon.aspx
should be allowed for anonymous users, but other pages should be accessible only to authenticated users.
1
You could refer to the implementation below.
Project structure:
In this project, only the user could access the page of the View
folder after logging in, and direct access to MainForm.aspx
will be denied and they will navigate to the Login.aspx
.
Login.aspx
<form id="form1" runat="server">
<div>
username: <asp:TextBox id="TxtUsername" runat="server"></asp:TextBox>
password: <asp:TextBox id="TxtPassword" runat="server"></asp:TextBox>
<asp:Button onclick="Submit_Click" runat="server" Text="Submit"/>
</div>
</form>
The following code, when the user successfully verifies the account and password, will be authorized to access through cookies.
Login.aspx.cs
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
var username = TxtUsername.Text;
var password = TxtPassword.Text;
if (username =="123" && password =="123") {
//Note: "admin" must be the same as <allow users="admin">
var ticket = new FormsAuthenticationTicket(1, "admin", DateTime.Now, DateTime.Now.AddMinutes(10), false, "MyRole");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
Response.Cookies.Add(cookie);
Response.Redirect("View/MainForm.aspx");
}
}
}
Web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx" name="LoginCookieName" defaultUrl="View/MainForm.aspx">
</forms>
</authentication>
…
</system.web>
<location path="Login.aspx">
<system.web>
<authorization>
<allow users ="*" />
</authorization>
</system.web>
</location>
<location path="View">
<system.web>
<authorization >
<allow users="admin"></allow>
<deny users ="?" />
<deny users="*"/>
</authorization>
</system.web>
</location>
1