Create login.aspx page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:TextBox runat="server" ID="txtUsername" /><br />
<asp:TextBox runat="server" ID="txtPassword" />
<asp:Button runat="server" ID="btnLogin" Text="Log in" OnClick="btnLogin_Click" />
<asp:Label runat="server" ID="lblStatus" />
</asp:Content>
login.aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
//If user is already login, it will redirect to Homenew.aspx page, with below code
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
Response.Redirect("Homenew.aspx");
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
if(txtUsername.Text== "12" && txtPassword.Text== "12")
{
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
}
else
{
lblStatus.Text="Incorrect password or id";
}
}
----------------------
Create Homenew.aspx page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<h1>Welcome</h1>
<h1><asp:Label runat="server" ID="lblWelcome" ></asp:Label></h1>
</asp:Content>
Homenew.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
//For showing current user name
lblWelcome.Text = Context.User.Identity.Name ;
}
Also a sign out button will be created which will be inside form tag (runat server)
aspx.cs
protected void logout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("loginnew.aspx");
}
aspx
<form id="form1" runat="server">
<asp:LinkButton OnClick="logout_Click" runat="server" class="nav_link"> <i class='bx bx-log-out nav_icon'></i> <span class="nav_name">SignOut</span> </asp:LinkButton>
</form>
-----------
In web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="loginnew.aspx" defaultUrl="Homenew.aspx" name=".ASPXFORMSAUTH"></forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
<system.web>
<system.webServer>
<defaultDocument>
<files>
<add value="loginnew.aspx" />
</files>
</defaultDocument>
</system.webServer>
reference:- https://www.c-sharpcorner.com/UploadFile/fa9d0d/forms-authentication-in-Asp-Net/
https://www.codeproject.com/Articles/2905/Role-based-Security-with-Forms-Authentication
No comments:
Post a Comment