Authenticate asp.net users after Azure AD - c#

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.

Related

how to update fields stored in a sqlite database within c#

i am making an application that lets a user register and login and also change their username sand passwords. when the user is signing up their details are stored in a sqlite database.my problem is that i am not able to update heir account details that are stored in the sqlite database
i have already looked up solutions to this onstack overflaw but i can tseem to find a solution
string oldusername = txtBoxoldUsername.Text;
string oldpassword = txtBoxoldPassword.Text;
string newusername = txtBoxnewUsername.Text;
string newpassword = txtBoxnewPassword.Text;
SQLiteConnection con = new SQLiteConnection("Data Source=Users.sqlite;Version=3;");
SQLiteCommand cmd = new SQLiteCommand("select * from UserInfo where UserName like #oldusername and Password = #oldpassword;", con);
cmd.Parameters.AddWithValue("#oldusername", oldusername);
cmd.Parameters.AddWithValue("#oldpassword", oldpassword);
con.Open();
SQLiteDataReader sdr = cmd.ExecuteReader();
if ((sdr.Read() == true))
{
//this is where i am trying to put the code that updats the users username and password
}
else
{
MessageBox.Show("Invalid username or password",
"Incorrect details entered");
}
i have tried everything i can but i still can seen to update my database.so it will be great if someone can code it in where i have left the comment the name for my database is Users and my table is called UserInfo
You need a seperate SQL Lite Command to make an update, somthing like:
SQLiteCommand cmd = new SQLiteCommand();
cmd.CommandText = "[Update SQL script]";
cmd.ExecuteNonQuery();

Check if for username and password the type is for a client or for a administrator

I just finished a database in C# with SQL. In my database I add data when I create the account for a person. I add the username, password, first and last name and the type (client or administrator).
When I am logging in all what I do is to check if username and password are correct. Here is the code.
private void button1_Click(object sender, EventArgs e)
{
con = new SqlConnection(#"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand("SELECT * FROM [dbo].[Cont] WHERE Username = #Username and Password = #Password;", con);
cmd1.Parameters.AddWithValue("#Username", this.Username.Text);
cmd1.Parameters.AddWithValue("#Password", this.Password.Text);
cmd1.Connection = con;
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd1);
da.Fill(ds);
con.Close();
bool loginSuccessful = ((ds.Tables.Count > 0) && (ds.Tables[0].Rows.Count > 0));
if (loginSuccessful )
{
MessageBox.Show("You logged in successfully!","Success!");
this.Visible = false;
f3.ShowDialog();
this.Visible = true;
}
else
{
MessageBox.Show("Invalid username or password!", "Error!");
}
}
And next what I want to do is to check if for this username and password the type is for client or administrator. And if is for administrator to entry in a form or if is for client to entry in another form.
How can I do? I need some ideas.
Here is the table:
You are retrieving the full row from your database table, so you have also retrieved the column that contains the usertype. You just need to check it after verifying the login
Here an example assuming that a "1" value means administrator, a "2" means normal user (of course you could change these constants to your actual values)
if (loginSuccessful )
{
string userType = ds.Tables[0].Rows[0]["Type"].ToString();
if(userType == "1")
{
// User is an administrator, go to admin form
}
else if(userType == "2")
{
// User is a normal user, go to user form
}
else
{
// Unexpected value, error message?
}
}
A side note, while you are using parameters there is still a security problem in your database/code logic. It seems that you store your password as a plain text. This could give to anyone that looks at your database table the possibility to know your users passwords. A password should never be stored in plain text. This site contains a lot of answer on how to correctly store passwords in a database
Start from here:
Best way to store passwords in a database

Get current logged in member user id

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.

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.

C# Windows Forms Application textbox validation against SQL DB

I'm new to C# and have a background in SQL so apologies if this is a very stupid query, but I have been trawling google for about 2 hours now and can't find what I need. If someone knows of an article they can point me to, that would be great.
I have a simple windows forms application, and I'm setting up a login box so that users have to enter their user ID to proceed.
I have a SQL Server DB (SQL 2005) with the following table:
Users
UserID (int); userName nvarchar(50)
I am using Visual Studio 2010
What I'm stymied by is how to check whether their userID exists in my SQL Table (called users...) I'm not going to put any code here because it's been rewritten from scratch so many times that a clean slate is probably best!
Ideally, I want the user to enter their user ID, and click 'login'. When they do this, if their userID is not valid in the DB table then I need it to give an error msgBox; if it is valid then it should log them in, passing their userID and userName (stored in the DB table) to a variable which I can use elsewhere in the application to populate fields.
I hope this makes sense, and I'm sure I've missed the perfect article out there which will explain it all - hopefully one of you kind people can point me in the right direction!
Thank you
You should make a simple SQL query with the userID the user entered, like
SELECT UserID from Users where userID= value. The executeNonQuery() will return the number of matches. If the returned value ==1, means that the userid exists in the database. If the returned value is different from 1, means that the userid not exists or it was registered multiple times. So, if is 1 then you cand call a different form to make different things, else you call anoter form or output a messagebox with an error message
/*table code
* create table login
(
id varchar(25),
pass varchar(25)
)
*
*
*
*
*/
string Connectstring = #"Data Source=DELL-PC;Initial Catalog=stud;Integrated Security=True";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(Connectstring);
cn.Open();
SqlCommand cmd = new SqlCommand("select * from log where id=#a and pass=#b", cn);
cmd.Parameters.AddWithValue("#a", textBox1.Text.ToString().ToUpper());
cmd.Parameters.AddWithValue("#b", textBox2.Text);
SqlDataReader dr = cmd.ExecuteReader();
if ((dr.Read() == true))
{
MessageBox.Show("The user is valid!");
Form2 mainForm = new Form2();
mainForm.Show();
this.Hide();
}
else
{
MessageBox.Show("Invalid username or password!");
}
}
Declare a connection string to Your database
string connString = #"Data Source=.\SQLEXPRESS;Initial Catalog=YourDatabase;Integrated Security=True";
After this You can use a validate method below
private bool ValidateUserById(string connString, int id)
{
using (var conn = new SqlConnection(connString))
{
conn.Open();
var sqlString = string.Format("Select * From Users where Id = {0}", id);
using (var cmd = new SqlCommand(sqlString, conn))
{
return cmd.ExecuteScalar() != null;
}
}
}
Then on button click You can check the user
if (ValidateUserById(connString, Convert.ToInt32(textBox1.Text)))
{
//..
}
else
{
//..
}

Categories