Forms Authentication - Accessing User Data - c#

I’m having some difficulty understanding how to access specific user data while using Forms Authentication.
I have already set up Forms Authentication for a User and an Admin.
When a User tries to log in, here is the code that runs:
protected void buttonLogIn_Click(object sender, EventArgs e)
{
string email = TextBoxEmail.Text.Trim();
string password = TextBoxPassword.Text.Trim();
UserType userType = UserType.User; //temporary value
string firstName = string.Empty;
string lastName = string.Empty;
bool success = DBAppLayer.AuthenticateLogIn(email, password, out userType, out firstName, out lastName);
if (success == true)
{
Session.Add("email", email);
Session.Add("firstname", firstName);
Session.Add("lastname", lastName);
switch (userType)
{
case DBDataLayer.UserType.User:
FormsAuthenticationUtil.SetAuthCookie(email, "User,", false);
Response.Redirect("~/User/UserDashboard.aspx", false);
break;
case DBDataLayer.UserType.Admin:
FormsAuthenticationUtil.SetAuthCookie(email, "Admin", false);
Response.Redirect("~/AdminArea/AdminDashboard.aspx", false);
break;
}
}
else
{
labelError.Text = "Bad username/password.";
}
}
This successfully redirects a User to their dashboard. Now when the User is in /User/UserDashboard.aspx, I want to display the User’s profile information that is stored in the database, such as the User’s job and age.
The problem is, I’m not sure how to access this specific User’s data in UserDashboard.cs. Do I need to create an Authentication Ticket? If so, would I do this in the login page?
Any links or suggestions would be appreciated.

It looks like your call to FormsAuthenticationUtil.SetAuthCookie passes in email as the user id when you create the authentication cookie. In your user dashboard page, the User.Identity.Name field will give you back this same email address. Use that value to call your database and get the user's profile.
You are also storing the email address in the Session so you could get it from there as well.

Related

Windows Universal App Get username from Microsoft Account Authentication

So I wanted the users to login to my app using Microsoft Account
I did all the setup in my mobile service in Azure and this is how I implement the login in my App:
private async Task<bool> AuthenticateAsync()
{
string message;
bool success = false;
try
{
user = await App.MobileService
.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
message =
string.Format("You are now signed in - {0}", user.UserId);
success = true;
}
catch (InvalidOperationException)
{
message = "You must log in. Login Required";
}
var dialog = new MessageDialog(message);
dialog.Commands.Add(new UICommand("OK"));
await dialog.ShowAsync();
return success;
}
all is working fine but all I get from this is a User Id.
and I need the name of the user that logged in, can anyone help me how should I go about this?
Thanks
and I need the name of the user that logged in, can anyone help me how should I go about this
For UWP app, this is impossible using official managed API. See MobileServiceAuthentication class in here
internal async Task<MobileServiceUser> LoginAsync()
{
string response = await this.LoginAsyncOverride();
if (!string.IsNullOrEmpty(response))
{
JToken authToken = JToken.Parse(response);
// Get the Mobile Services auth token and user data
this.Client.CurrentUser = new MobileServiceUser((string)authToken["user"]["userId"]);
this.Client.CurrentUser.MobileServiceAuthenticationToken = (string)authToken[LoginAsyncAuthenticationTokenKey];
}
return this.Client.CurrentUser;
}
The official sdk just retrieves the userId and MobileServiceAuthenticationToken, for other platform, we need to use GetIdentitiesAsync() method to get identity, see How to get user name, email, etc. from MobileServiceUser? or LINK
The username info actually has been retrieved in the SSO process:
So you have to implement the auth process(Extend the method based on the open source code) and maintain the username information as you need.
If you can get the user's input, maybe you can also call Live API: https://msdn.microsoft.com/en-us/library/office/dn659736.aspx#Requesting_info

How to find OldPassword to let the user change it

I'm working on an intranet, I've just added a feature on the user's profile to change his password.
As you can see with the following controller :
[HttpPost]
public ActionResult ChangePassword(Employee objToEdit, FormCollection form, LocalPasswordModel model) // Find how to obtain "OldPassword" from AccountModel
{
objToEdit.Login = User.Identity.Name;
string name = objToEdit.FirstName;
string pwd = form["NewPassword"];
string confirm = form["ConfirmPassword"];
if (_service.Edit_password(objToEdit, pwd, confirm)) // Checks if NewPassword and ConfirmPassword are the same, and does some syntax checking
{
bool changePasswordSucceeded;
try
{
changePasswordSucceeded = WebSecurity.ResetPassword(WebSecurity.GeneratePasswordResetToken(objToEdit.Login), pwd); // Seems to work
}
catch (Exception)
{
changePasswordSucceeded = false;
}
if (changePasswordSucceeded)
{
return RedirectToAction("Index", new { Message = CRAWebSiteMVC.Controllers.AccountController.ManageMessageId.ChangePasswordSuccess });
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
return new RedirectResult(Url.Action("Index"));
}
return View();
}
So far, the user just needs to input a New password and a confirmation password. I wish to add a "Enter your current Password" feature but I can't find a way to retrieve the user's current password !
The user profile DB does not contain a Password column anymore and I use Form authentication if that's of any help.
EDIT: Thank you for your help, to solve my problem I simply replaced the ResetPassword line by the following :
changePasswordSucceeded = WebSecurity.ChangePassword(objToEdit.Login, current, pwd);
If it fails, it directly displays the error message that the current password is wrong.
You can't !
That's actually a security feature. You should never store a password in plain text.
The good thing is, you don't need to do the comparison yourself:
Instead, use something like ValidateUser to let the Membership Provider validate the provided password. Behind the scenes, this method will hash the password and compare it with the hashed version contained in the database.
EDIT:
Also, note that since you are using the WebSecurity class, there is a method, ChangePassword that accepts the current password. It seems that method will check the current password matches the specified currentPassword parameter. Maybe you should use this one instead of ResetPassword

role based authorization with window authentication in asp.net

I have to create a role based application in which i have three roles admin,manager and user. In my application i have three different folder in which i have to check those role. What i want is when i enter credential in my login page first it will check whether user is authorized or not and if not then redirect to the error page. If authorized then check its roles and give access to the specified folder.
this is my login page code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
String queryread = #"Select * from Login where UserName = '" + tbUserName.Text.ToLower() + "' and Password='"+ tbPassword.Text.ToLower() +"'";
SqlConnection con = new SqlConnection();
SqlDataReader read;
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["BartConnectionString"].ConnectionString;
SqlCommand readdata = new SqlCommand(queryread, con);
try
{
con.Open();
read = readdata.ExecuteReader();
Boolean flag = false;
while (read.Read())
{
String UserName = read["UserName"].ToString().ToLower();
String password = read["Password"].ToString();
if (tbUserName.Text.ToLower() == UserName)
{
if (tbPassword.Text.Trim() == password)
{
Session["UserID"] = UserName.ToString();
flag = true;
}
}
}
if (flag)
{
Response.Redirect("~/Supervisor/Form.aspx", false);
}
else
{
Response.Redirect("~/Error.aspx",false);
}
}
catch (Exception ex2)
{
Response.Write("Error");
}
finally
{
if (con.State == System.Data.ConnectionState.Open)
con.Close();
}
}
in this i check the authorization for the user now i also want to check which role this user have what changes i have to make in this code to check roles also
In my sql i have table login which have
UserID
UserName
Password
RoleID
what changes i have to make in my web.config file. what change i have to make in my login page to check role. I guess my question is clear to you guys.
Thanks in advance
As I said in the comment above I wouldn't accept this code into a project I was managing and you should be very careful about how you implement user authentication in an application. I would start by having a good read of this document on MSDN:
Security Basics and ASP.NET Support
Overview of Forms Authentication
Forms Authentication Configuration and Advanced Topics
Once you have that in place you can have a look at Roles in this article:
Authenticating Users with Forms Authentication
There is a lot to take in here but reading through these will give you a good base to start from.
Even though you want to use Windows Authentication I would still read the above linked articles as they will give you a lot of useful information about how authentication work in general. To use Windows Authentication with ASP.NET read this:
Windows Authentication in ASP.NET

Cookies and session in asp.net

I am creating a login and the storing the user details in a cookie using this code
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
{
//string useremail = Convert.ToString(txtUserName.Value);
Session.Add("useremail", txtUserName.Value);
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), 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);
}
I am also creating a session Session.Add("useremail", txtUserName.Value);
After succesfull authentication it is redirected to user.aspx
I want to read the useremail value in the user.aspx page but when I tried to access the value in the user page it is not showing useremail field.
protected void Page_Load(object sender, EventArgs e)
{
if
(Session["useremail"] == null) Response.Redirect("Home.aspx");
else
BindGridView(useremail);
}
And this is my webconfig:
<authentication mode="Forms"><forms name=".YAFNET_Authentication" loginUrl="Home.aspx" protection="All" timeout="43200" cookieless="UseCookies"/></authentication>
Correct me if i am doing any wrong. And also please tell me how to pass the useremail value to the user.aspx page so that I can pass that value to gridview function
Just change it to
protected void Page_Load(object sender, EventArgs e)
{
if (Session["useremail"] == null)
Response.Redirect("Home.aspx");
else
BindGridView((string)Session["useremail"]);
}
You can add an object to the session state like this:
Session["useremail"] = "john.smith#microsoft.com";
You can then retrieve it in the following manner:
var useremail = Session["useremail"] ?? null;
if (useremail == null)
{
//...
}
else
{
BindGridView(useremail);
}
If the item "useremail" is not present in the session state the useremail variable will be set to null otherwhise it will contain the e-mail address.
You are getting confused with relationship between authentication, session state and cookies.
In ASP.NET, Session State and Forms Authentication are not linked i.e. their scope are different. You can have some session state for un-authenticated user. Session and forms authentication uses different cookies for tracking purposes and the cookie management is more or less automatic and you don't really need to write code to manage it as you have done. Besides, what you store in the cookie has no bearing on what goes in the session state. Its also possible to have both session and forms authentication to get working w/o cookies. So code such as below should work for session state
Session["key"] = "put your data here";
// retrieve the data elsewhere
var data = Session["key"];

ASP.NET Forms Authentication authenticates in localhost server, but not on the web server

I've been implementing the Forms Authentication in ASP.NET with C# (v3.5).
I created a simple login form, when the users' email & passwords are stored in my SQL db.
When I login in my localhost, everything works just fine, but when I published the project and uploaded it on to my production web server, things got a little bit wierd for me.
The HttpContentxt.Current.User.Identity.IsAuthenticated variable return false, even if the login was successfull (and again, in localhost everything works fine).
This is the following login button click code (I'm using my own DataAccess, ignore it's irrelevant code):
protected void btnLogin_Click(object sender, EventArgs e)
{
Page.Validate("Login");
if (Page.IsValid)
{
string email = txtEmail.Text;
string passwd = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "MD5");
WebFactory.DataAccess.Users.Data userData = new WebFactory.DataAccess.Users.Data(ConnectionString);
userData.Load(new WebFactory.DataAccess.Users.Item[] {
new WebFactory.DataAccess.Users.Item(WebFactory.DataAccess.Users.Columns.Email, email),
new WebFactory.DataAccess.Users.Item(WebFactory.DataAccess.Users.Columns.Password, passwd)
});
if (userData.HasData) // Login Success
{
if (!cbRememberMe.Checked)
{
FormsAuthentication.SetAuthCookie(userData.Id.ToString(), false);
}
else
{
FormsAuthentication.Initialize();
DateTime expires = DateTime.Now.AddDays(20);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
userData.Id.ToString(),
DateTime.Now,
expires,
true,
String.Empty,
FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authCookie.Expires = expires;
Response.Cookies.Add(authCookie);
}
lblStatus.Text = "";
if (Common.QS.HasRefUrl)
{
Response.Redirect(Common.QS.RefUrl);
}
else
{
Common.UserTools.RedirectLoggedInUser(userData.Id);
}
}
else // Login failed
{
lblStatus.Text = "Email or password is wrong. please try again."
}
}
}
Thanks for all helpers, and sorry for the english mistakes.
Thanks all, I solved the problem.
I just needed to enter a name attribute in the <forms> clause and everything works perfectly now.
Thanks again!
Try checking the Forms Authentication Configuration in your web.config. Specifically the domain and path variables. The domain should match the domain of your website and the path should match the application folder name. You probably won't have one of these, so just set it to "/"
You can also set up tracing to make sure that the cookie is actually being read by the application.

Categories