Quantcast
Channel: Security
Viewing all articles
Browse latest Browse all 4737

FORM BASED AUTHENTICATION WITH DATABASE AND ASSIGNED ROLES

$
0
0

Below is my code .I have 3 columns in my database i.e 'UserName','Password','UserType'

What I want to do is :  if the usertype='admin' it will redirect to..aaa.aspx

                                 if the usertype='user' it will redirect to..bbb.aspx

public partial class login : System.Web.UI.Page
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["str"].ConnectionString.ToString());

    protected void Page_Init(object sender, EventArgs e)
    {
        this.btnLogin.Click += new System.EventHandler(this.btnLogin_Click);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    private bool ValidateUser(string userName, string passWord)
    {
        SqlCommand cmd;
        string lookupPassword = null;

        try
        {
            conn.Close();
            conn.Open();

            cmd = new SqlCommand("Select Password from Admin where Username=@userName", conn);
            cmd.Parameters.Add("@userName", SqlDbType.VarChar, 20);
            cmd.Parameters["@userName"].Value = userName;

            lookupPassword = (string)cmd.ExecuteScalar();

            cmd.Dispose();
            conn.Dispose();
        }
        catch (Exception ex)
        { }
        if (null == lookupPassword)
        {

            return false;
        }

        return (0 == string.Compare(lookupPassword, passWord, false));

    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        if (ValidateUser(txtUsername.Text, txtPassword.Text))
        {
            FormsAuthenticationTicket tkt;
            string cookiestr;
            HttpCookie ck;
            tkt = new FormsAuthenticationTicket(1, txtUsername.Text, DateTime.Now,
            DateTime.Now.AddMinutes(5), chkPersistCookie.Checked, "your custom data");
            cookiestr = FormsAuthentication.Encrypt(tkt);
            ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
            if (chkPersistCookie.Checked)
                ck.Expires = tkt.Expiration;
            ck.Path = FormsAuthentication.FormsCookiePath;
            Response.Cookies.Add(ck);

            string strRedirect;
        }
    }
}


Viewing all articles
Browse latest Browse all 4737

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>