Thursday, March 22, 2012

Authentication not working!

Hey there,

I have a table [user] in a SQLExpress database [Database.mdf] in the App_Data folder. There are two columns. [userId] and [password]. I want to authenticate the user who wants to log in through a Login control. the user should have his userId and password in the [user] table. I digged and made my code. but it doesn't work it keeps giving me that the user is not authenticated. i guess it has no errors. please tell me if you find the error. here is the code:

1protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)2 {3 SqlConnection conExpress =new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True;User Instance=False");//Create the server connection45try6 {7string id_user = Login1.UserName.Trim();//Get the username from the control8string pass_user = Login1.Password;//get the Password from the control910 //These are a sql and connection Examples11string sql ="SELECT userId, password FROM user WHERE userId = @.param_Id AND password = @.param_Password";12 SqlCommand comSQL =new SqlCommand(sql, conExpress);//Create the sql command using sql string and sql connection1314 //Add the sql parameters15 comSQL.Parameters.AddWithValue("@.param_Id", id_user);//New on VS 2.016 comSQL.Parameters.AddWithValue("@.param_Password", pass_user);1718string cod_user ="";19string name_user ="";2021//Open database connection22 conExpress.Open();23 SqlDataReader dr = comSQL.ExecuteReader();24while (dr.Read())25 {26 cod_user = dr.GetValue(0).ToString();//The coduser is unique onto database table27 name_user = dr.GetValue(1).ToString();28 }29 conExpress.Close();//Close Database Connection30if (cod_user !="")//The user exist onto database31 {32//Create the session vars33 Session["coduser"] = cod_user;34 Session["nameuser"] = name_user;35 e.Authenticated =true;//Grant the access, Goes to DestinationPageUrl36 }37 }38catch(Exception)//On Login Error39 {40 e.Authenticated =false;//Confirm that you are out41 conExpress.Close();//On any error case, close the database connection42 }43 }

The way I've used the Login control with custom authentication (without MembershipProvider) is

processing the event of the Login Control:

protected

void Login1_LoggingIn(object sender,LoginCancelEventArgs e)

and if the credentials is valid i create the autheentication cookie:

FormsAuthentication.SetAuthCookie(userName,false);

and Redirect to the page user has requested.

If the credentials are wrong I set :

e.Cancel =

true;

and

Login1.FailureText =

"Unable to validate credentials";

I'm not sure this is the right way of doing that, but it works for me.

Hope this will help you.

Cheers,

Yani

sql

No comments:

Post a Comment