Why do I have 2 ASPXAUTH cookie instead of 1? - c#

i am creating an asp.net application, it's already working by now, but the problem is when i use "Live HTTP Headers" i found that my site have 2 ASPXAUTH cookie, and the one being used is the bottom one.
here i give a screen shoot what i found:
btw here is some of my code in login page :
string email = tbEmail.Text;
string pass = tbPass.Text;
bool remember = cbRemember.Checked;
var res = (from user in ctx.users
where user.password == ctx.ConvertPassword(pass)
&& user.email == email
select user).FirstOrDefault(); // Remark : 0 = active, 1 = Inactive, 2 = Suspend, 3 = Unconfirmed
if (res != null && res.email.ToLower() == email.ToLower())
{
if (res.userstatus == 0 || res.userstatus == 3)
{
FormsAuthentication.SetAuthCookie(email, remember);
FormsAuthentication.RedirectFromLoginPage(email, remember);
var arr = Request.Cookies.AllKeys;
}
else if (res.userstatus == (int)UserStatus.Inactive)
{
lblMessage.Text = "You have deleted your account, if you wish to restore it, please click ";
btRecover.Visible = true;
}
else if (res.userstatus == (int)UserStatus.Suspended)
{
lblMessage.Text = "Your account has been suspended, for more information, please contact our support";
}
else
{
lblMessage.Text = "Invalid username or password";
}
}
else
{
lblMessage.Text = "Invalid username or password";
}
what i do wrong?

The
FormsAuthentication.SetAuthCookie(email, remember);
sets the cookie. But also does
FormsAuthentication.RedirectFromLoginPage(email, remember);
which is a higher level facade - not only sets the cookie but also redirects from the login page to the redirecturi pointing page.

Related

Use session state to redirect user to homepage if already logged in

I have a login page and and a accounts controller with Login action. When I log in I get redirected to home page(which is good) but after logging in if I re visit the login page it shows the login form again (although I am logged in).
I tried check for session state values but every time I try to use it I get null reference error.
public ActionResult Login(string name, string password, string hash)
{
if (!string.IsNullOrWhiteSpace(name))
{
var user = _model.tblUsers.FirstOrDefault(x => x.username == name);
if (user != null)
{
if (user.powerLevel == 0)
{
Session["IsAdmin"] = (user.password == password);
Session["IsAuthor"] = null;
Session["IsUser"] = null;
}
else if (user.powerLevel == 1)
{
Session["IsAdmin"] = null;
Session["IsAuthor"] = (user.password == password);
Session["IsUser"] = null;
}
else if (user.powerLevel == 2)
{
Session["IsAdmin"] = null;
Session["IsAuthor"] = null;
Session["IsUser"] = (user.password == password);
}
else
{
return View("Login");
}
return RedirectToAction("Index","Posts");
}
}
return View("Login");
}
so if either of IsAdmin, IsAuthor, IsUser Session is set to true I want to get redirected to homepage. I tried check it with string.IsNullOrWhiteSpace but it doesnt work I always get false even if the Session is set to true

Log in through active directory

I want to create LogIn button through Active Directory.
So i have an idea to take Name logged user(Windows) from his Domain:
string Name = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
and then take Group for Login above:
string Group = System.Security.Principal.WindowsIdentity.GetCurrent().Groups.ToString(); // <---I think this is wrong ?
string allowedGroup = "Admins";
then something like:
if(Name == string.Empty)
{
MessageBox.Show("Your Name in domain doesn't exist");
}
if(Group.ToString() != allowedGroup)
{
MessageBox.Show("You don't have permissions to log in");
}
else
{
MessageBox.Show("Hello");
}
I think my 'getting group' is wrong. How can I do it? I don't know how to exactly search for one or two groups where User is assigned.
What about when user is assigned to many Groups?
Here is the point to use windows identity to authorize login.
1) Get the windows identity of user.
2) Use Windows identity object to get the other information like name and group.
use group name to validate user request.
Hope this will help you. Please write in comment in you have any questions.
System.Security.Principal.WindowsIdentity WI = System.Security.Principal.WindowsIdentity.GetCurrent();
string sUserName = WI.Name;
bool bAuthorized = false;
string allowedGroup = "Admins";
IdentityReferenceCollection irc = WI.Groups;
foreach (IdentityReference ir in irc)
{
if(ir.Translate(typeof(NTAccount)).Value == allowedGroup)
{
bAuthorized = true;
break;
}
}
if(string.IsNullOrEmpty(sUserName))
{
MessageBox.Show("Your Name in domain doesn't exist");
}
if(bAuthorized == false)
{
MessageBox.Show("You don't have permissions to log in");
}
else
{
MessageBox.Show("Hello");
}
Ok, i got this. Thanks for Pankaj.
System.Security.Principal.WindowsIdentity WI = System.Security.Principal.WindowsIdentity.GetCurrent();
string sUserName = WI.Name;
bool bAuthorized = false;
string allowedGroup = "Admins";
IdentityReferenceCollection irc = WI.Groups;
foreach (IdentityReference ir in irc)
{
NTAccount accInfo = (NTAccount)ir.Translate(typeof(NTAccount));
if (accInfo.Value == allowedGroup)
{
bAuthorized = true;
break;
}
}
if(string.IsNullOrEmpty(sUserName))
{
MessageBox.Show("Your Name in domain doesn't exist");
}
if(bAuthorized == false)
{
MessageBox.Show("You don't have permissions to log in");
}
else
{
MessageBox.Show("Hello");
}

Not case-sensitive save in SQL?

On my login form after i save my content to SQL and if i try to get the information from the database the information passes the evaluation to true even if the information provided is typed both ways - upper case or lower case.Here is my login code,please help me understand.I'am contacting database with Entity Framework.the currUser is a variable where I save the current user information.
try
{
if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
{
var users = from c in context.CustomerTables where c.username == username && c.password == password select c;
List<CustomerTable> table = users.ToList();
if (table.Any())
{
MessageBox.Show("Successfully logged in.\nWelcome " + username + "!", "Welcome", MessageBoxButton.OK, MessageBoxImage.Asterisk);
currUser.username = username;
currUser.password = password;
return true;
}
else
{
MessageBox.Show("Username or password is invalid.", "Error logging in", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
}
else
{
MessageBox.Show("Username and password format is invalid!","Null username or password",MessageBoxButton.OK,MessageBoxImage.Warning);
return false;
}
The simplest fix would be to replace
if (table.Any())
with
if (table.Any() && table[0].username == username && table[0].password == password)
The reason why this would work is that string comparison in C# is case-sensitive by default.

How do I show a message box if the username is not in a database? C#

Hi all I have a University project and I am coding a login screen, my text book is far too vague and I can't figure out how to show a message box if the user name is not inside the database. Here is my code:
public void login()
{
//try
//{
var tbl = from s in this.database1DataSet.employee
where s.Username == userNameBox.Text
select s;
foreach (var s in tbl)
{
if (s.Username == userNameBox.Text && s.Password == passwordBox.Text)
{
MessageBox.Show("Access granted welcome " + s.fName);
this.Close();
}
else
{
MessageBox.Show("Access denied invalid login details");
}
}
//}
/*catch (SyntaxErrorException)
{
MessageBox.Show("User Does not exist");
}*/`enter code here`
If your where clause doesn't match any users, there won't be any rows in the results.
Therefore, your loop will never execute.
Instead, you can call FirstOrDefault() to get the first result row, or null if there aren't any.
You can check for existance of a user like:
if(!database1DataSet.employee.Any(r=> r.Username == userNameBox.Text))
{
MesasgeBox.Show("User does not exist");
}
Also IMO, its better if you check the user name and password together, and show a message like "Invalid Username/password" instead of multiple messages.
var user = database1DataSet
.employee
.FirstOrDefault(r=> r.Username == userNameBox.Text &&
r.Password == passwordBox.Text)
if(user != null)
{
MessageBox.Show("Access granted welcome " + user.fName);
this.Close();
}
else
{
MessageBox.Show("Invalid username/password");
}
Also see: Why encrypt user passwords?
I believe you want:
var user = (from s in this.database1DataSet.employee
where s.Username == userNameBox.Text &&
s.Password == passwordBox.Text
select s).FirstOrDefault();
if(user != null{
MessageBox.Show("Access granted welcome " + s.fName);
this.Close();
}
else{
MessageBox.Show("Access denied invalid login details");
}
void login()
{
var tbl = from s in this.database1DataSet.employee
where s.Username == userNameBox.Text
select s;
if(tbl.Count() == 0)
{
MessageBox.Show("User Does not exist");
return; // or this.Close(); if it's what you want
}
foreach (var s in tbl)
{
if (s.Username == userNameBox.Text && s.Password == passwordBox.Text)
{
MessageBox.Show("Access granted welcome " + s.fName);
this.Close();
}
else
{
MessageBox.Show("Access denied invalid login details");
}
}
First of all, assuming your usernames are unique, you will only ever have 0 or 1 values in tbl. That's fine, but be aware of it. Second, you're wanting to have different functionality of the size of tbl is 0, or 1. This is easily done with an if statement. If there is an entry, check credentials. Otherwise, show an error message for invalid username. Since this is a course project, I won't actually write sample code for you, but that should be enough to get it working. Good luck!

Code does not return if the condition is true

I need to validate if the user's provided information is in the database, i've tried to enter the correct condition and its not working it returns an error that it cannot be found on the database. Can you check my code and tell me what's going on? , I tried to debug it but the foreach loop continue to loop and does not go to if (isexist) statement
protected void btnSubmit_Click(object sender, EventArgs e)
{
token = FormsAuthentication.HashPasswordForStoringInConfigFile(txtUsername.Text.ToString() + txtAcctNo.Text.ToString(), "MD5");
try
{
bool isExist = false;
DataSet ds = new DataSet();
ds = startService.getAllUsersWithoutFilter();
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dRow in ds.Tables[0].Rows)
{
string userName = dRow["UserName"].ToString();
string acctNo = dRow["AccountNumber"].ToString();
string question = dRow["SecretQuestion"].ToString();
string answer = dRow["SecretAnswer"].ToString();
if (userName == txtUsername.Text.ToString() && acctNo == txtAcctNo.Text.ToString() && question == cboQuestion.Text.ToString() && answer == txtAnswer.Text.ToString())
{
isExist = true;
}
else
{
isExist = false;
}
}
if (isExist)
{
startService.sendTokenizer(txtUsername.Text.ToString(), token);
//update database to change password to standard password
startService.inserUserActivity(txtUsername.Text.ToString(), txtAcctNo.Text.ToString(), "Password Reset Request", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
startService.requestReset(txtUsername.Text.ToString(), txtAcctNo.Text.ToString(), token);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "<br>We have sent an email to you for the instructions to reset your password. Please check your email.";
}
else
{
this.lblMessage.ForeColor = System.Drawing.Color.Red;
this.lblMessage.Text = "<br><br>Error - Information cannot be found. Please check and try again. Make sure all the fields are correct.";
}
}
}
catch
{
lblError.Text = "There was an error occured while processing your request. Please try again later.";
}
}
I think all you need is to break out of your foreach loop when you set isExist to true.
if (userName == txtUsername.Text.ToString() && acctNo == txtAcctNo.Text.ToString() && question == cboQuestion.Text.ToString() && answer == txtAnswer.Text.ToString())
{
isExist = true;
break; //Found it, so stop looking.
}
I think Joel's right about a direct answer to your question.
I would add that you should reconsider loading the entire users table and iterating through it on the web server. Why not just try to select a matching row from the database? If you get a match, the credentials were valid. If not, they were not valid.
#Dhenn: you need to make following changes in your code
protected void btnSubmit_Click(object sender, EventArgs e)
{
token = FormsAuthentication.HashPasswordForStoringInConfigFile(txtUsername.Text.ToString() + txtAcctNo.Text.ToString(), "MD5");
try
{
bool isExist = false;
DataSet ds = new DataSet();
ds = startService.getAllUsersWithoutFilter();
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dRow in ds.Tables[0].Rows)
{
string userName = dRow["UserName"].ToString();
string acctNo = dRow["AccountNumber"].ToString();
string question = dRow["SecretQuestion"].ToString();
string answer = dRow["SecretAnswer"].ToString();
if (userName == txtUsername.Text.ToString() && acctNo == txtAcctNo.Text.ToString() && question == cboQuestion.Text.ToString() && answer == txtAnswer.Text.ToString())
{
// if exist execute following code
startService.sendTokenizer(txtUsername.Text.ToString(), token);
//update database to change password to standard password
startService.inserUserActivity(txtUsername.Text.ToString(), txtAcctNo.Text.ToString(), "Password Reset Request", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
startService.requestReset(txtUsername.Text.ToString(), txtAcctNo.Text.ToString(), token);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "<br>We have sent an email to you for the instructions to reset your password. Please check your email.";
}
else
{
// id not exist then execute following code
this.lblMessage.ForeColor = System.Drawing.Color.Red;
this.lblMessage.Text = "<br><br>Error - Information cannot be found. Please check and try again. Make sure all the fields are correct.";
}
}
}
}
catch
{
lblError.Text = "There was an error occured while processing your request. Please try again later.";
}
}

Categories

Resources