I have an ASP.NET solution that launch a website, with a login page.
Also, I have created many Sql server accounts that give access to the same databases.
I want that, when an user put his username & password in my login page, my app try to connect to Sql server using this username & password.
So I don't have a table with the usernames & passwords of the users in my database, but I have many SQL server accounts with theses usernames & passwords.
I hope I'm clear enough.
So, I want to know, when my app try to connect to Sql server, if the username & password that the user enters doesn't refer to any account, if we can display an error message.
So the user know that he enters his credentials incorrectly, and he can try to enter theml again.
Is it possible ?
Thanks for your help and have a nice day.
So I would think you can build the connectionstring up and then just add the username and password and then attempt to connect. You can encase it in a try catch block and if it fails you can display a message on the form or you can work out what the error from the try catch block is saying and display your own message.
Something like this
<add key="ConnectionString" value="server=serverName;database=database;User ID=username;password=password"/>
could be
SqlConnection con = new SqlConnection();
try
{
string connectionString = #"<add key="""ConnectionString""
value="""server=serverName;database=database;User ID="" + txtUsername.Text + """;password="" + txtPassword.Text +"""/>";
con = new SqlConnection(connectionString);
con.Open();
}
catch (exception ex)
{
read ex.message
}
Then you can use the following to see if connection was sucessful
if (con.State = ConnectionState.Open)
{
your code here...
}
Related
I have this project I am working on for an assignment, and I have a question working with ASP.NET and SQL Server. I have a login page that kinda works, but there are two tables that I need to get data from - users (subscribers) and admin page but am unsure how to access both of them as I can only access one.
public void login(Object src,EventArgs e)
{
get_connection();
try
{
connection.Open();
command = new SqlCommand("SELECT * FROM subscribers WHERE Email = #Email AND Password = #Password", connection);
command.Parameters.AddWithValue("#Email", loginName.Text);
command.Parameters.AddWithValue("#Password", loginPass.Text);
//command = new SqlCommand("SELECT * FROM admin WHERE Email =#Email and Password = #Password", connection);
//command.Parameters.AddWithValue("#Email", loginName.Text);
//command.Parameters.AddWithValue("#Password", loginPass.Text);
reader = command.ExecuteReader();
I commented out the admin part because when I include it, only admin username and password is accepted and not subscribers. What would I need to do to fix this?
The "admin part" causes you to only get records from the admin table because you're destroying and recreating your SqlCommand object. You'll need to create a new command in a different variable and read from it separately. There are ways to get multiple recordsets in the same call but I don't recommend it in this case.
That out of the way... Normally I'd expect to see a single users table with permissions/roles granted elsewhere. Consider something like the out of the box ASP.NET membership provider to take care of these implementation details for you:
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-use-the-aspnet-membership-provider
I'm creating a register page . When I write connection string to connect to SQL Server 2014 , this error is shown: Error Pic
protected void btnsignup_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=(local);DataBase=MyDataBase;integrated security=True");
SqlCommand cmd = new SqlCommand("insert into Users (Username,UPassword,Uname,UEmail) values ('"+ tbUname.Text + ","+ tbPass.Text + ","+tbname.Text +","+ tbemail.Text +"')");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Like the error message shows you cannot login as that user (IIS/defaultapppool) on SQL server.
Ususally this happens if:
User does not exist
User does not have the permissions to access the database
Go to your SQL server management studio and make or edit your user. right click the security folder to make a new user, and make sure he is databaseReader, -Editor and/or databaseAdmin
You can also specify another user in your connectionstring by adding: User ID=name;Password=password
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.
This is my first time trying to use a database in ASP.Net, and I have a problem here:
My database is on my computer (localhost), and it throws an exception on me when I click the "submit" button :
SQLException was unhandled by user code. Login failed for user ".
protected void Register_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("server = localhost ;uid=; Password= database = Movies;");
connection.Open();
//FirstName***********
string firstName = UsernameTextBox.Text;
string sqlquery = ("INSERT INTO [Movie] (FirstName) VALUES (' " +FirstNameTextBox.Text + " ' ");
SqlCommand command = new SqlCommand(sqlquery , connection);
command.Parameters.AddWithValue("FirstName", firstName);
Since the server is on my computer, I dont have any username, right?!
You do need a username and password, or else you need to use integrated security, which means that your windows credentials are used.
You can add integrated security to your connection as follows:
SqlConnection connection = new SqlConnection("server = localhost ;integrated security=SSPI; database = Movies;");
A good resource for connection strings is http://www.connectionstrings.com
SQL server always requires a username, whether it's on your machine or a remote machine.
I'd suggest looking www.asp.net or try Google to find out how you configure your patricular version of SQL Server
Check this site for connectionstrings if you have problem with formating the connectionstring
I have the following code snippet.
SqlCommand cmd = new SqlCommand("SELECT FName,LName FROM EMPLOYEE_TABLE WHERE EmployeeID = '" +TextBox1.Text + "' AND Password = '"+ TextBox2.Text +"'", con);
SqlDataReader x = cmd.ExecuteReader();
try
{
if (x.Read())
{
name = (string)x["FName"] +' '+ (string)x["LName"];
Session["NAME"] = name;
Session["ID"] = TextBox1.Text;
Response.Redirect("sample.aspx?action=On_Click");
}
else
{
errormsg.Text = "login failed.Please enter Valid UserID and Password";
errormsg.ForeColor = System.Drawing.Color.Red;
}
}
catch (Exception exp)
{
errormsg.Text = "Sorry,You dont have access to this portal.";
}
finally
{
x.Close();
con.Close();
}
Now, when i use a valid id (that exists) and password as abc' or 'x'='x then it logs in into the first account of the table in the database. Till this it's fine.
However when I try to debug the code, it throws an error Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack..
Also if it is throwing an error then why is it logging into this 1st account of the database. Note: the first account of the database has a different userid than that which i m providing.
Note: I am the developed of this application. So I'm not doing anything illegal. :)
Look at this part of your SQL:
"' AND Password = '"+ TextBox2.Text +"'"
With your password, it's
"' AND Password = ''x'='x'"
which is not the SQL you want.
Even if you are trying to do SQL injection, you have to result in valid SQL. Usually, it's by ending the statement with a semi-colon after closing the quote. See this:
http://xkcd.com/327/
OK, to provide an answer based on the primary issue you've got (as you've stated, you're new to the SQL Injection issue).
SQL Injection is caused by dynamically building a SQL query using user input as part of the construction. The simplest solution to this in .Net is to create a parameterized query.
I think Jeff Atwood has the most complete yet concise article providing an explanation and complete example here
Quoted from above link:
SqlConnection conn = new SqlConnection(_connectionString);
conn.Open();
string s = "SELECT email, passwd, login_id, full_name " +
"FROM members WHERE email = #email";
SqlCommand cmd = new SqlCommand(s);
cmd.Parameters.Add("#email", email);
SqlDataReader reader = cmd.ExecuteReader();
The issue at hand:
The reason it's still logging into the account is because the query is still "valid".
The statement will still be executed, and the relevant record will still be returned from the database, no exception will be thrown.
The only way you will stop the login process when invalid data is provided is to validate the input before executing the query. You should always validate user input before sending it off to the database. If the user were to provide:
username'; drop table users;--
as the username, you would be in a LOT of trouble.
The error you're encountering is a debugging error, not an actual program exception. That's why it works when you run it normally.
To remedy the error, I'd first make sure that everything is running with a Debug build. Also, make sure you're currently debugging in the function of the variable you want to inspect. Try stepping (F10) a few times past your breakpoint to refresh the context. There are a slew of other suggestions on the internet for that particular error, so if you're still having problems you might have to do some googling.