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.
Related
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();
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.
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.
This is a simple login page with 2 panels. Panel for login where user enters user name and password. I validate if username is present and do this:
string query = "SELECT UserName,HashedPassword,SaltString FROM users WHERE UserName='"+txtUserName.Text+"'";
using(SqlConnection con = new SqlConnection(connection))
{
con.Open();
SqlCommand cmd=new SqlCommand(query,con);
SqlDataReader sdr = cmd.ExecuteReader();
if (!sdr.Read())
{
pnlLogin.Visible = false;
pnlRegister.Visible = true;
}
else
{
//validate password and redirect
}
I remember to have done same thing a few times before, although I don't have the code with me. I use form authentication in web.config. Please tell me where I am going wrong. Thanks in advance.
And one if I comment this:
pnlLogin.Visible = false;
the pnlRegister becomes visible.
If pnlRegister is nested in (a child of) pnlLogin, and you hide pnlLogin, pnlRegister will also be invisible.
Since you didn't provide markup, this is a guess based on the behavior you described.
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
{
//..
}