Get current logged in member user id - c#

I have an asp.net web app and i have an issue when two or more users on the same network are logged in . I use a query to retrieve account details which sometimes retrieves the details of the other person logged in on the same network.
Example
John are Lisa are logged in with different devices and different account on the same WiFi.
Sometime Lisa's Account Details appear as John's details on his account and same happens to lisa.
This is an example of the query
// Determine the currently logged on user's UserId value
MembershipUser currentUser = Membership.GetUser();
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
// Retrieve profile Name
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string selectSql = "SELECT (FirstName + ' ' + LastName) FROM User_Profile WHERE UserId = (#UserId)";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(selectSql, myConnection);
myCommand.Parameters.AddWithValue("#UserId", currentUserId);
Label1.Text = myCommand.ExecuteScalar().ToString();
myConnection.Close();
}
I am not sure if this issue arises from
MembershipUser currentUser = Membership.GetUser();
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
, the query or i am not doing something right.
Thank you.

The object currentUser contains a property UserName. Try displaying that to determine that you have the right user is the first place.

Check the worker threads on IIS, they can become crossed and set all sessions to the same thread. Usually if this happens, they will change to the last person to log in.

Related

How to get the username when they login and store it to database [duplicate]

This question already has answers here:
How do I get the current username in .NET using C#?
(18 answers)
Closed 2 years ago.
I want to get the username when users login, after that, when they want do vote for a particular candidate, they click the vote button, then the users's username will be store in the database. Any suggestion on how to do it? For the display of the candidate details(for voting), i use the gridview, now, I able to store the candidate details in the database, just left the username of the voter.
protected void LinkButton_Click(Object sender, EventArgs e)
{
String MyConnection2 = "Server=localhost;database=ovs;Uid=root;password=; Convert Zero Datetime=True";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
Label lblStudentId = (Label)grdrow.Cells[0].FindControl("lblID");
string studentId = lblStudentId.Text;
String query = "insert into voting (studentID,)values ('" + lblStudentId.Text + "')";
MySqlCommand MyCommand2 = new MySqlCommand(query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
}
MyConn2.Close();
}
}
When the users click the vote button, the candidateID that being displayed in the gridview will be store to the database.However, I want to store who vote for the particular candidate (store they studentID). I'd like capture thier username when they login, and when they click the vote button, insert their studentID to the database
Session["UserName"] = txtID.Text;
txtID.Text = Session["UserName"].ToString();
I store the session in the user login page. How can I store it to the database using the insert command(when they click the vote button)?
Use Viewstate or Session object to store the username. Then retrieve the username from that.
Set value to session or viewstate
Session["Username"]=txtusername.Text;
Viewstate["Username"]=txtusername.Text;
get value from session or viewstate
Response.Write(Session["Username"].ToString());
Response.Write(Session["Username"].ToString());

Obtaining data from SQLite file C#

Hi guys can somebody instruct me on how to solve this problem. I am connecting to a database in the bin debug file whilst using SQLite. I want to check if the login details of the user are correct and when the code verifies that the login details are correct I want to check if the person has registered as a administrator or in this case lecturer however when I don't know how to pull the data from the specific user that has logged in to check if they are a lecturer. There is my code:
string Query = string.Format("SELECT [username], [password], [isLecturer] FROM users");
SQLiteConnection DataBaseConnection = new SQLiteConnection(ConnectionString);
SQLiteCommand Command = new SQLiteCommand(Query, DataBaseConnection);
DataBaseConnection.Open();
using (var reader = Command.ExecuteReader())
{
while (reader.Read())
{
if ((reader.GetString(0) == txtUsername.Text) && (reader.GetString(1) == txtpassword.Text))
{
string Query2 = string.Format("SELECT [isLecturer] FROM users WHERE ");
if ((reader.GetString(2) == "1"))
{
this.Hide();
FetchingTheMainConwaysForm(1);
}
else if ((reader.GetString(2) == "0"))
{
this.Hide();
FetchingTheMainConwaysForm(0);
}
break;
}
else
{
MessageBox.Show("Username or password incorrect", "Authentication Problem", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
DataBaseConnection.Close();
You are selecting whole table in the code. This will make your app slow. I will suggest to send user name and password to the database like below
SELECT [username], [password], [isLecturer] FROM users WHERE [username]=txtUsername.Text AND [password]=txtpassword.Text
If this query returns a row this means it is a successful login otherwise show error message to user.
Now, for successful login use that selected columns through out the code.
My suggestion, Don't use column like [isLecturer]. Make it Role and add values like administrator, lecturer, student etc. (Standard way is to create one more table with RoleId and Role, and use that RoleId in your main table) So in future you can add more roles without doing any more changes in code. You can easily compare user role and give privileges/features depending on role.
And add trim and more validations.

I am running a web app and want to update my SQL Server user profile database with C# code but no matter what I do I cannot get it to work

I am trying to create a MyAccount page for a website I am making using ASP.NET and Bootstrap with html and C# running in the background for our objects. We are using SQL Server to run our databases and I am having a LOT of troubles getting my updates to go through. I am using a test user profile I had my partner hard insert into the system as I have not programmed the account creation system yet, only the login.
The issue is that when I run my update code the SQL Server database does not update with the passed information. I receive no exceptions and I know my connection string works as I use it to log in and drag contents of my database into text boxes on the main screen. Because of this I have no idea why it is not updating and I feel very lost.
I have removed bits of the connection string itself as this server is not my own and I don't want my professor's personal connection and login credentials being on the internet.
My debug label running a query tells me each time I attempt to change the state variable on the item that 1 row was effected.
The user profile I am trying to update has the following information stored in it.
Username: MarshallE
Email: Test1234
Password: Test1234!
First Name: Marshall
Last Name: Emmer
Properties Rented: Prime Place
Universities Attended Oklahoma State University
State: N/A (My partner just added this and didn't update the profile)
Here is my code I used to try and update the thing:
protected void btnRegAcctUpdate_Click(object sender, EventArgs e)
{
// This unit's job is to update the database of the specified user with the info in the text boxes
// Make sure the password fields are the same
if (txtAcctPass1.Text == txtAcctPass2.Text)
{
lblAcctDebug.Text = "";
SqlConnection MyConnection = new SqlConnection();
MyConnection.ConnectionString = "Server= (N/A ;Database=F19_groupRoss;User Id=groupRoss;Password = (N/A);";
string MyUpdateStatement;
MyUpdateStatement = "UPDATE dbo.UserID SET Email = #Email, Password = #Password, FirstName = #FirstName, LastName = #LastName, Universities = #University, Town = #Town, State = #State" + " WHERE UserID = #UserID";
SqlCommand MySqlCmd = new SqlCommand(MyUpdateStatement, MyConnection);
// These are the values we will be overriding the database with
MySqlCmd.Parameters.AddWithValue("#UserID", (string)Session["UserID"]);
MySqlCmd.Parameters.AddWithValue("#FirstName", txtAcctFirstName.Text);
MySqlCmd.Parameters.AddWithValue("#LastName", txtAcctLastName.Text);
MySqlCmd.Parameters.AddWithValue("#Email", txtAcctEmail.Text);
MySqlCmd.Parameters.AddWithValue("#Password", txtAcctPass1.Text);
MySqlCmd.Parameters.AddWithValue("#State", txtAcctState.Text);
MySqlCmd.Parameters.AddWithValue("#Town", txtAcctTown.Text);
MySqlCmd.Parameters.AddWithValue("#University", txtAcctUniversity.Text);
// Open the connection
MyConnection.Open();
int rows = MySqlCmd.ExecuteNonQuery();
lblDebug2.Text = "Rows affected: " + rows;
MyConnection.Close();
}
else
{
lblAcctDebug.Text = "Error: Please ensure the text in the new password and password confirmation boxes are identical";
}
}
If anyone can tell me what I am doing wrong I would REALLY appreciate it!
Try adding your parameters like this:
MysqlCmd.Parameters.Add(New Parameter(#FirstName, txtAcctFirstName.text));

Authenticate asp.net users after Azure AD

I have an application that will only be used by employees in my organisation. This will be restricted with Azure Active Directory, so only users within the domain will be able to access the site.
After that I need to add further security so only certain employees access the site. I have a (MS) SQL table with all the usernames that are eligible.
The username will be lifted directly from the Azure Active Directory by using
string username = User.Identity.Name;
(this has been tested and returns the correct syntax and string etc)
My first thought was to use forms authentication, then on the "login.aspx" Page_Load, check against the SQL table and if exists then continue into the site
FormsAuthentication.RedirectFromLoginPage(username, true)
And if not then load the login.aspx page with a form to fill out to request access.
Question is, is this the best way to do it, without re-writing the entire solution.
I have multiple aspx pages inside the site so don't want to add the "check" to each page.
The users won't need to enter a password.
EDIT 25/12/17 Thanks to #juunas and #PeterBons - this is what i have got in my Page_load event of my login form, then web.config handles the forms authenication.
Can anyone see any MASSIVE error or flaw in security?
protected void Page_Load(object sender, EventArgs e)
{
bool isAuthenticated = false;
string username = User.Identity.Name.ToLower().Trim();
string firstname = "";
string surname = "";
string jobrole = "";
string userlevel = "";
string constr = ConfigurationManager.ConnectionStrings["AzureSQL"].ConnectionString;
SqlConnection cnn = new SqlConnection(constr);
string query = "Select * from Usernames";
string querywriteTime = "update [usernames] set [last log in] = #date where username = #username";
SqlCommand cmd1 = new SqlCommand(querywriteTime, cnn);
SqlCommand cmd2 = new SqlCommand(query, cnn);
cnn.Open();
SqlDataReader rdr = cmd2.ExecuteReader();
while (rdr.Read())
{
if (rdr[0].ToString().ToLower().Trim() == username)
{
firstname = rdr[1].ToString().Trim();
surname = rdr[2].ToString().Trim();
jobrole = rdr[4].ToString().Trim();
userlevel = rdr[5].ToString().Trim();
isAuthenticated = true;
}
}
cnn.Close();
if (isAuthenticated)
{
string str = firstname + "/" + surname + "/" + jobrole+"/"+userlevel;
cmd1.Parameters.AddWithValue("#date", DateTime.Now);
cmd1.Parameters.AddWithValue("#username", username);
cnn.Open();
cmd1.ExecuteNonQuery();
cnn.Close();
FormsAuthentication.RedirectFromLoginPage(str, true);
}
}
You can set the app to require user assignment in the Azure portal.
Go to portal.azure.com
Find Azure Active Directory
Go to Enterprise applications
Go to All applications
Find your app
Go to Properties
Tick User assignment required?
Now you can go to the Users and groups tab and select who has access.

ASP.NET - C# - Retrieve username and compare to SQL database

I have a SQL database named "administration" with usernames and roles.
What I would like to do with my ASP.NET application is:
once someone accesses my intranet site, I get their username using
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
Then I check if that username is in my database. I assume I can do this with an IF EXISTS statement.
However I'm not sure how I would do the following: IF the user is in the database I want to display the Web Page as per their role (i.e. all pages are different Admin = see all content and buttons, User = all content no buttons).
However if their username is not in my database I will display a blank page or something along the lines of "Access Denied".
This is the way I have been asked to do it but I cant seem to work it out.
Is it possible?
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
after getting userName.
sqlconnection cn = new sqlconnection("give connectionstring");
cn.open();
sqlcommand cmd = new sqlcommand();
cmd.commandtext = "select * from "table"; // table name give.
cmd.connection = cn;
sqldatareader rdr = cmd.executereader();
while(rdr.read()){
if(stringName = rdr[columnnumber].toString());
flag = true;
}
if(flag)
//take decesion
else
// take decesion.
cn.close();
you can achieve it like this. u can use. it. bt there are some mistake in syntax i roughly write for u.

Categories