session variable for username - asp.net

Hey I am creating a forum where users can login and post ocmments in a forum, I want the username as a session variable so I can get it when they post a comment and insert the username in the db and also to display a hello user message.
Below is my login code:
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
localhost.Service1 myws = new localhost.Service1();
ds = myws.GetUsers();
foreach (DataRow row in ds.Tables[0].Rows)
if (txtusername.Text == System.Convert.ToString(row["username"]) &&
txtpassword.Text == System.Convert.ToString(row["password"]))
{
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(txtusername.Text, false);
}
else
Label3.Text = "Invalid Username/Password";
}
Do I declare the session variable here?
Like:
Session["username"] = "username";
Also not sure what to type to get the value username from the db
Thanks

You don't need to use a session. Once you call the FormsAuthentication.RedirectFromLoginPage method, inside the target page you could access the currently connected user from the authentication cookie that was emitted by this method using User.Identity.Name.
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
string username = User.Identity.Name;
// ...
}
}
To learn more about how Forms Authentication works in ASP.NET I invite you to read the following article.

You are already using forms authentication (FormsAuthentication.RedirectFromLoginPage(txtusername.Text, false)) which is great. Consequently, you don't need to store the username is session as it's already available via User.Identity.Name, as Darin noted.
I have written two tutorials on forms authentication you might find useful:
An Overview of Forms Authentication
Forms Authentication Configuration and Advanced Topics
Additionally, consider using Membership. Membership is a subsystem built into ASP.NET that handles user accounts and provides an API for creating accounts, deleting accounts, etc. In short, you don't have to write all that code yourself. And with the login Web controls, creating new accounts, signing users in, resetting passwords, and so on, are all quite simple and involve zero to little code. For more information see my Membership tutorials.
Happy Programming!

Related

Email confirmation and Password Policy Without ASP.NET Identity

I am using OWIN form authentication in my project and not using any Identity specific classes that MVC templates generate.
I want to implement email confirmation and a password policy in my project. I'm not sure how this can be accomplished, as I don't have Identity related classes in my project as I don't want to use those. I am happy with the OWIN form authentication.
Is there any way I can verify via email and create a password policy by using OWIN form authentication?
I am not expert but Yes you can , To verify Email address you can send email with Guid as QueryString and add page to check id Guid is true and then flag user as confirmed did you mean like this ?
Send Email as html :
body = "<b>Wellcom Mr " + Username + " </b>";
body += "<br />";
body += "<b><a href=http://YourDomain/checkuseremail.aspx?
UserId=" + userId + " style='display:block; '>confirm</a></b>";
public partial class checkuseremail: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["UserID"];
if(id != null){ select user id if email correct redirct to success page and flag user as confirmed}
else {redirct to error page}
}}

ASP.NET Impersonation design

This is my ASP.NET authentication operation.
private void LoginButton_Click(Object sender,
EventArgs e)
{
string userName = txtUserName.Value;
string password = txtUserPass.Value;
if (ValidateUser(txtUserName.Value, txtUserPass.Value))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(3), chkPersistCookie.Checked,
userName + "#ticket");
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;
strRedirect = Request["ReturnUrl"];
if (strRedirect == null)
strRedirect = "MyAccount.aspx";
Response.Redirect(strRedirect, true);
}
else
Response.Redirect("logon.aspx", true);
}
I have User table in my db where all credentials are saved. Using ValidateUser method I am doing credentials validation. Also I have three type of users: Member, Moderator and Administrator. Each type of members has unique functionality. Lets say I have A, B and C T-SQL stored inside in my db.
What should I to to let for:
Member execute only A query.
Moderator execute A and B.
Administrator execute A,B and C.
Of course, I can manage execution from Web app, but I am not sure how safe it is. Technically I can execute similar query outside of App, which gives access to all db data. I want somehow combine Web App login and Db access as well.
Thanks!
If these queries are going to come from the web app, I think you would want to manage the code side that invokes the procedures.. you could maintain a list of urls in your database, assign roles, and give these roles access to specific urls. These urls would dictate what queries a user could execute...
then in your code you could assign custom attributes to limit access to them....
http://msdn.microsoft.com/en-us/library/ff647396.aspx

How to provide different pages on login for different users?

I'm working on web application which has a database
UserName|Password|UserType
Anil|Anil|Manager
ghouse|Ghouse|Admin
raghu|raghu|User
Now my task is to provide each user their own page on login...They all have a same login page.
I tried this code it's working fine for two users. What to do if I have more than two users?
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DebitCareBankApp;Data Source=SSDEV7-HP\\SQLEXPRESS");
string cmdStr = "select LoginType from Login where UserName='" + TxtUsername.Text + "' AND Password = '" + TxtPassword.Text + "'";
SqlCommand cmd = new SqlCommand(cmdStr, con);
con.Open();
Object TypeUser = cmd.ExecuteScalar();
con.Close();
if (TypeUser != null)
{
LblError.Visible = false;
LblError.Text = "";
if (TypeUser.ToString() == "Manager")
Response.Redirect("~/CallingAgents/CallingAgents_Login.aspx");
else
Response.Redirect("~/UserRegistrationForm.aspx");
}
else
{
LblError.Visible = true;
LblError.Text = "Invalid Credentials Entered, Try again";
}
I think you should create a common class where insert your user type on successful login.
In that common class redirect it to respective page.
On successful login:
Response.Redirect(clsCommon.GetDefaultPage(userType));
your commaon class code:
public static string GetDefaultPage(string userType){
//Default Redirects
Dictionary<string, string> userInfo = new Dictionary<string, string>(){
{"Manager","~/ManagerLogin.aspx"}, {"Admin","~/AdminLogin.aspx"},
{"User","~/UserLogin.aspx"}
};
return userInfo[roleName];
}
If you are using struts then you can redirect to different pages depending upon some Id. In actionforward you can achieve so. Or you can get some values from the url and try to redirect it
A simple way would be to use the Login-control and provide event handlers for the Authenticate event and the LoggedIn event. But i think it would be worth while for you to check out the capabilities of the asp.net membership system.
I assume you are not using Membership provider and make your login functionality by hand.
I do not fully understand the purpose of this customization. It make no sense for me. But there are multiple solutions for you:
convert the login page (aspx) into a user/custom control (ascx) and put in into different pages - simple, quick but not fully transparent, more info ScottGu
use IIS URL-Rewrite engine to provide multiple entry-points (urls)
to the same login page - clear, recomended, more info ScottGu
With first scenario you need to check UserType for credentials given by the user and confront it with page Url (aspx). In the second scenario, you need to obtain Request.RawUrl which contain base Url and make simple case.
Make use of sessions.
For a workaround, you can follow this:
+provide the same login page.
+Ask for username and password.
+use a drop down for selecting the usertype (ie Admin or Manager or User).
So based on the selection from drop down list you process the request.
I hope this helps.

Asp.Net 4 Response.Cookies.Add does not add cookie to users machine

I am trying to setup a basic Form Authentication using ASP.NET 4.
I know my validation code (code that checks if the username and password is correct) is working because after if the user enters invalid information the ReturnLable tells them so. However if they enter the correct information, they are redirected to the restricted page with a 403 – Forbidden error. When I check the shell:cookie path no cookie has been written even though I added it to the collection “Response.Cookies.Add(cookie);”
protected void Submit_Click(object sender, EventArgs e)
{
Email.Text = Email.Text.Trim();
Password.Text = Password.Text.Trim();
if (IsValid(Email.Text, Password.Text)) //user exists
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
Email.Text,
DateTime.Now,
DateTime.Now.AddMinutes(50),
RememberMe.Checked,
"user",
FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
Response.Cookies.Add(cookie);
}
else
{
ReturnLable.Text = "<font color=red> Username/Password Incorrect Please Try Again </font>";
ReturnLable.Visible = true;
}
From this MSDN article:
If you do not set the cookie's expiration, the cookie is created but
it is not stored on the user's hard disk. Instead, the cookie is
maintained as part of the user's session information. When the user
closes the browser or if the session times out, the cookie is
discarded.
Thus, a cookie could be successfully set, alive and well in the browser, but have no corresponding file in the "cookies" folder on the hard drive.
make sure that Enable anonymous access is disabled on IIS and Integrated Windows security is enabled

ASP.NET login control

I intend to use membership.authentication/authorization API from ASP.NET 2.0 in in ASP.NET 3.5 web app. However, when I implement the LoggedIn method for a login component as below:
protected void Login1_LoggedIn(object sender, EventArgs e)
{
Label1.Text = User.Identity.Name;
}
the Name comes as a null value... the username/pass are correct, the login control works fine if the default behavior is used, but it seems that the Identity is not properly initialized. Any ideas on how to get the current User object with the associated values?
Thanks
You may need to check User.IsAuthenticated is true first
You can use Membership.GetUser method to accomplish the same thing:
Label1.Text = Membership.GetUser().UserName

Resources