login redirect doesn't work

G

gorden blom

Hello,

I'm working on a asp.net/C# project, but I haven't got a lot of
experience with programming with C# and the dotnet framework. I've
build a login screen at witch users can login. All goes fine until I
try to redirect the user to the protected pages. Can anyone help me?
The code is as followed:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Security;
using Microsoft.ApplicationBlocks.Data;

public class login : System.Web.UI.UserControl {

public System.Web.UI.WebControls.TextBox txtUsername;
public System.Web.UI.WebControls.TextBox txtPassword;
public System.Web.UI.WebControls.Button btnLogin;
public System.Web.UI.WebControls.Label lblOutput;


#region Web Form Designer generated code
override protected void OnInit(EventArgs e) {
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent() {
this.btnLogin.Click += new
System.EventHandler(this.btnLogin_OnClick);
}
#endregion


public void btnLogin_OnClick(object sender, System.EventArgs e) {

lblOutput.Text = "";


SqlConnection sqlCon = new
SqlConnection(ConfigurationSettings.AppSettings.Get("DBconString"));

if(txtUsername.Text != ""){

if(txtPassword.Text != ""){

try {

sqlCon.Open ();

string strSql = ("select count (*) from login where
username = '"+ txtUsername.Text +"' and password = '" +
txtPassword.Text +"'") ;

SqlCommand command = new SqlCommand(strSql, sqlCon);

int count = (int) command.ExecuteScalar ();

if (count > 0) {
string strSqlGetRole = ("select role from login
where username = '"+ txtUsername.Text +"' and password = '" +
txtPassword.Text +"'");
SqlCommand commandGetRole = new
SqlCommand(strSqlGetRole, sqlCon);
string strRole = (string)
commandGetRole.ExecuteScalar();
FormsAuthentication.SetAuthCookie
(txtUsername.Text, true);
Response.Redirect("ProtectedPage.aspx");
}
else {
lblOutput.Text = "login failed!!";
}
}

catch (SqlException ex) {
Console.WriteLine("Error: {0}", ex.Errors[0].Message);
}

finally {
sqlCon.Close ();
}
}
else {
lblOutput.Text = "Enter Password";
}
}
else {
lblOutput.Text = "Enter Username";
}
}

}


The web.config file is like this:

<configuration>
<appSettings>
<add key="DBconString" value="server='(local)';
trusted_connection=true; database='ATD_db'"/>
</appSettings>
<system.web>
<authentication mode="Forms">
<forms name="AuthCookie" loginUrl="logincontrol.aspx"
protection="None" timeout="30" path="\"></forms>
</authentication>
<authorization>
<deny users="?"></deny>
</authorization>
</system.web>
</configuration>

Can anyone help me?
 
L

Lauchlan M

build a login screen at witch users can login. All goes fine until I
try to redirect the user to the protected pages.

Well, what happens when you try to redirect the user?

Also, maybe try first working with RedirectFromLoginPage instead of
Response.Redirect, as this does the login behind the scenes. When this works
you can go back to setting up the cookie yourself.

If you do set up the authentication cookie yourself, you will probably have
to code the global.asax authentication handler.

HTH

Lauchlan M
 
G

gorden blom

Lauchlan M said:
Well, what happens when you try to redirect the user?

When I push the login button, I'll see no error message. I'm sure that
my input is correct because that is handeled by my code, it will
display something in the lblOutput when something is wrong or input
isn't correct.

the address bar is: http://localhost/login.aspx?ReturnUrl=/secret/ProtectedPage.aspx
but it doesn't redirect or authenticate the user so I'll be stuck on
the login page.
Also, maybe try first working with RedirectFromLoginPage instead of
Response.Redirect, as this does the login behind the scenes. When this works
you can go back to setting up the cookie yourself.

When I use the RedirectFromLoginPage, I have to delete 2 lines en
replace them by 1:
FormsAuthentication.RedirectFromLoginPage (txtUsername.Text, true);
but this gave me the same result as above with the redirect, I think
my code doesn't authenticate the right way.
If you do set up the authentication cookie yourself, you will probably have
to code the global.asax authentication handler.

HTH

Lauchlan M

Hope you can help me out!
 
L

Lauchlan M

Well, what happens when you try to redirect the user?
When I push the login button, I'll see no error message. I'm sure that
my input is correct because that is handeled by my code, it will
display something in the lblOutput when something is wrong or input
isn't correct.

the address bar is: http://localhost/login.aspx?ReturnUrl=/secret/ProtectedPage.aspx
but it doesn't redirect or authenticate the user so I'll be stuck on
the login page.

The gist of it looks ok. I wouldn't do it exactly the same: I would use a
visual component rather than creating the command component at runtime, I
would use one SQL query that returns the username and role where username =
(username) and password = (password) rather than two queries and I would use
a datareader to look at the dataset. But the approach you took should work.

From the url, it has tried to redirect but has been redirected back to the
login page.

Do you have any code in your global.asax? This might be relevant if you do.

Also, in your web.config, you use ' path="\" ' in your authentication. Try
path ="~\" instead, to make it relative to the web application root.

HTH

Lauchlan M
 
M

Me2

Gorden,

You have quite a way to go!! Keep plugging, you will get there.

First off you need to use the RequiredFieldValidator on the .aspx page to
enforce the user enter values in the userid and password fields. This will
cause the validation to occur on the users computer saving a round trip to
the server if the user fails to enter values.

I the Click code:
You first check to see that the page validations occurred properly
if (Page.IsValid)...
Next form your SQL request
string strSql = ("select count (*) from login where username = '"+
txtUsername.Text +"' and password = '" + txtPassword.Text +"'") ;
SqlCommand command = new SqlCommand(strSql, sqlCon);
Do Open and execute SQL in try block
try
{sqlCon.Open ();
int count = (int) command.ExecuteScalar ();
}
catch
{ lblOutput.Text = "login failed!!";
}
finally
{sqlCon.Close ();
}
Do another try catch block for each SQL command
if (count)
{try
{
....

Hope this helps,

--
Ralph Page MBA, CMBA, MCDBA, MCSE, CCNA
-------------------------------------------------------------------------
"However beautiful the strategy, you should occasionally look at the
results."
-- Winston Churchill
-------------------------------------------------------------------------
gorden blom said:
Hello,

I'm working on a asp.net/C# project, but I haven't got a lot of
experience with programming with C# and the dotnet framework. I've
build a login screen at witch users can login. All goes fine until I
try to redirect the user to the protected pages. Can anyone help me?
The code is as followed:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Security;
using Microsoft.ApplicationBlocks.Data;

public class login : System.Web.UI.UserControl {

public System.Web.UI.WebControls.TextBox txtUsername;
public System.Web.UI.WebControls.TextBox txtPassword;
public System.Web.UI.WebControls.Button btnLogin;
public System.Web.UI.WebControls.Label lblOutput;


#region Web Form Designer generated code
override protected void OnInit(EventArgs e) {
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent() {
this.btnLogin.Click += new
System.EventHandler(this.btnLogin_OnClick);
}
#endregion


public void btnLogin_OnClick(object sender, System.EventArgs e) {

lblOutput.Text = "";


SqlConnection sqlCon = new
SqlConnection(ConfigurationSettings.AppSettings.Get("DBconString"));

if(txtUsername.Text != ""){

if(txtPassword.Text != ""){

try {

sqlCon.Open ();

string strSql = ("select count (*) from login where
username = '"+ txtUsername.Text +"' and password = '" +
txtPassword.Text +"'") ;

SqlCommand command = new SqlCommand(strSql, sqlCon);

int count = (int) command.ExecuteScalar ();

if (count > 0) {
string strSqlGetRole = ("select role from login
where username = '"+ txtUsername.Text +"' and password = '" +
txtPassword.Text +"'");
SqlCommand commandGetRole = new
SqlCommand(strSqlGetRole, sqlCon);
string strRole = (string)
commandGetRole.ExecuteScalar();
FormsAuthentication.SetAuthCookie
(txtUsername.Text, true);
Response.Redirect("ProtectedPage.aspx");
}
else {
lblOutput.Text = "login failed!!";
}
}

catch (SqlException ex) {
Console.WriteLine("Error: {0}", ex.Errors[0].Message);
}

finally {
sqlCon.Close ();
}
}
else {
lblOutput.Text = "Enter Password";
}
}
else {
lblOutput.Text = "Enter Username";
}
}

}


The web.config file is like this:

<configuration>
<appSettings>
<add key="DBconString" value="server='(local)';
trusted_connection=true; database='ATD_db'"/>
</appSettings>
<system.web>
<authentication mode="Forms">
<forms name="AuthCookie" loginUrl="logincontrol.aspx"
protection="None" timeout="30" path="\"></forms>
</authentication>
<authorization>
<deny users="?"></deny>
</authorization>
</system.web>
</configuration>

Can anyone help me?
 
G

gorden blom

Me2 said:
Gorden,

You have quite a way to go!! Keep plugging, you will get there.

First off you need to use the RequiredFieldValidator on the .aspx page to
enforce the user enter values in the userid and password fields. This will
cause the validation to occur on the users computer saving a round trip to
the server if the user fails to enter values.

I know I can use te RequiredFieldValidator on my .aspx page but I want
to keep my login as small(size) as possible, If I use a
RequiredFieldValidator on my page(I have to use 2, 1: txtUsername 2:
txtPassword) it will use up lot's of space. Is there a way to check 2
fields with one RequiredFieldValidator?
I the Click code:
You first check to see that the page validations occurred properly
if (Page.IsValid)...
Next form your SQL request
string strSql = ("select count (*) from login where username = '"+
txtUsername.Text +"' and password = '" + txtPassword.Text +"'") ;
SqlCommand command = new SqlCommand(strSql, sqlCon);
Do Open and execute SQL in try block
try
{sqlCon.Open ();
int count = (int) command.ExecuteScalar ();
}
catch
{ lblOutput.Text = "login failed!!";
}
finally
{sqlCon.Close ();
}
Do another try catch block for each SQL command
if (count)
{try
{
....

I think putting each sql statement in a try catch block should supply
me more detailed error messages so I should do that.
 
G

gorden blom

Lauchlan M said:
The gist of it looks ok. I wouldn't do it exactly the same: I would use a
visual component rather than creating the command component at runtime, I
would use one SQL query that returns the username and role where username =
(username) and password = (password) rather than two queries and I would use
a datareader to look at the dataset. But the approach you took should work.

You're right I should use a datareader that returns a dataset. It will
be less difficult to read the code, and it should result in better
preformance because I only query once.
From the url, it has tried to redirect but has been redirected back to the
login page.

Do you have any code in your global.asax? This might be relevant if you do.

I don't have any code in my glabal.asax. What can be relevant to place
there in my case?
Also, in your web.config, you use ' path="\" ' in your authentication. Try
path ="~\" instead, to make it relative to the web application root.
I tried this but it didn't work, same result as before.
 
M

Me2

I know I can use te RequiredFieldValidator on my .aspx page but I want
to keep my login as small(size) as possible, If I use a
RequiredFieldValidator on my page(I have to use 2, 1: txtUsername 2:
txtPassword) it will use up lot's of space. Is there a way to check 2
fields with one RequiredFieldValidator?

If your goal is to save bandwidth and time to transfer the data, tell me
which is faster, to transfer the page back and forth from the server to the
user three times for each error, or one time with a larger page with
validators?
 
G

gorden blom

Me2 said:
If your goal is to save bandwidth and time to transfer the data, tell me
which is faster, to transfer the page back and forth from the server to the
user three times for each error, or one time with a larger page with
validators?

I'm sorry, I was't clear enough. Yes, I know the validators are more
efficient, but I can only use 150px x 200px for my control, when I use
the validators it uses more then te space gave me to build te login
in. Is there a way to use 1 validator for 2 fields, or do you suggest
an other way to do it?
 
M

Me2

I'm sorry, I was't clear enough. Yes, I know the validators are more
efficient, but I can only use 150px x 200px for my control, when I use
the validators it uses more then te space gave me to build te login
in. Is there a way to use 1 validator for 2 fields, or do you suggest
an other way to do it?

Gorden,

As far as I know, you can not use a validator on more than one field.
 
L

Lauchlan M

If you haven't got this working yet, try getting someone elses example code,
getting that working, and then seeing what they are doing differently to
what you were doing.

HTH

Lauchlan M
 
G

gorden blom

Lauchlan M said:
If you haven't got this working yet, try getting someone elses example code,
getting that working, and then seeing what they are doing differently to
what you were doing.

HTH

Lauchlan M

Thank you for all your replies, I will search for some working code so
I can compare that one with my code.

Gorden Blom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top