Wednesday, January 5, 2011

Forms Authentication

form authenication code
in web.config
----------------------------
 <authentication mode="Forms">
      <forms loginUrl="Login.aspx">
        <credentials passwordFormat="Clear">
          <user name="vineet" password="vineet123"/>
          <user name="venu" password="venu"/>
          <user name="satheesh" password="satheesh"/>
        </credentials>
      </forms>
     
    </authentication>
    <authorization>
      <deny users="?"/>
     
    </authorization>

in login.aspx
-----------------
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Windows.Forms;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void btn_login_Click(object sender, EventArgs e)
    {
        if (FormsAuthentication.Authenticate(TextBox1.Text, TextBox2.Text) == true)
        {
            FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false);
            Response.Redirect("~/Inventory/InventoryHome.aspx");
        }
        else
        {
          MessageBox("INVALID");
        }
       
    }
   
protected void MessageBox(string msg)
{
lbl.Text = "<script language='javascript')>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
Page.Controls.Add(lbl);
}
}




in web.config Write as
===============
<system.web>
<authentication mode="Forms">
<forms loginUrl="UI/login.aspx"
defaultUrl="UI/DashBoard.aspx"
name="abc"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>

In login.aspx Source Html Write as
========================
<asp:TextBox ID="txt_UserName" runat="server"></asp:TextBox>
<asp:TextBox ID="txt_Password" runat="server"></asp:TextBox>

<asp:Button ID="btn_login" runat="server" onclick="btn_login_Click"
Text="Login" />

in login.aspx.cs code behind Write as

=========================
protected void btn_login_Click(object sender, EventArgs e)
{
Session["UID"] = txt_UserID.Text;
int i=Convert.ToInt32(sc.User_Login(txt_UserName.Text, txt_Password.Text));
if (i < 1)
{
alertBox("Invalid User....");
}
else
{

FormsAuthentication.RedirectFromLoginPage(txt_UserName.Text, false);
FormsAuthentication.SetAuthCookie("txt_UserName.Text",false);

}
}



public void alertBox(string msg)
{
Label1.Text = "<script type='text/javascript'>"+Environment.NewLine+"window.alert('"+msg+"')</script>";
Page.Controls.Add(Label1);
}


and in default2.aspx page write in Logout Button click as
========================================================
protected void lnkbtn_LogOut_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect(Request.Path);
}



No comments: