Create Sql Server Authentication Account? - c#

I want to create an Sql Server Authentication Account, not a user in the database or in the account.
What i mean is that i want to create an account so i can login from it when i start the sql server, using SQL Transaction or using C#.

There are only two modes that I know you can use: Windows or SQL Server Authentication. This means you are limited to only two choices: You either use a Windows account, or you create an SQL Server login that you can use to authenticate.
EDIT:
To programmatically create an sql server login, you could use Sql Server Management objects. I notice you didn't say whether you want to do this from a Windows (desktop) or Web application. To use Sql Server Management to create a login (or do any sort of "management"), the code would need to run with higher privileges - say local or domain account with sufficient privileges to administer the SQL server instance.
You will need to add references to (you could use version 9.0 of the assemblies):
Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Smo
Microsoft.SqlServer.SqlEnum
With that, the following code is enough to create an SQL login and also add the user to your target database
var serverName = "."; // Your SQL Server Instance name
var databaseName = "Test"; // Your database name
var loginName = "testuserY"; // Your login name (should not exist - or you should add code to check if the login exists)
Server svr = new Server(serverName);
var db = svr.Databases[databaseName];
if (db != null)
{
// You probably want to create a login and add as a user to your database
Login login = new Login(svr, loginName);
login.DefaultDatabase = "master"; // Logins typically have master as default database
login.LoginType = LoginType.SqlLogin;
login.Create("foobar", LoginCreateOptions.None); // Enter a suitable password
login.Enable();
User user = new User(db, loginName);
user.UserType = UserType.SqlLogin;
user.Login = login.Name;
user.Create();
// add a role
user.AddToRole("db_owner");
}
You will need to add:
using Microsoft.SqlServer.Management.Smo;
You can add try{} catch{} blocks and plumbing code to make it more robust you would recover gracefully in case of failure

Related

Why is SQL Server using a different user to create the session?

I am trying to connect to SQL Server database from a .NET Core web application,
here is the connection string I am using:
Server =.; Database = DBNAME; User Id = tb; Password = pass; Trusted_Connection = True; MultipleActiveResultSets = True;.
The previous setup generates an exception:
An error occurred using the connection to database 'DBNAME' on server '.'.
System.Data.SqlClient.SqlException (0x80131904): Error opening session for the user 'MyDomain\ServerMachineName$'.
I think it is trying to connect using another domain account that I don't even see in the list of database users under security tab, nor in the users of the server instance.
In the startup file, the related configuration is:
services.AddDbContext<MyDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnectionString")));
I tried adding different users with the required privileges to the SQL Server instance and to the particular DB, but none of these worked.
Questions:
Why is the system completely ignoring the connection string I am specifying?
Is there a work around to this?
What Trusted_Connection = True; means is ignore the passed in user id and password and instead use the windows credentials of the user running the program. As your program is likely running as a service the "user" it runs as is MyDomain\ServerMachineName$.
Setting trusted connection to false will have it use the userid and password provided in the connection string.

How can I create a contained user on an Azure SQL database using C#?

I need to create a contained user for my Azure SQL database using C#. I have the following code already for creating the database:
// Login to Azure
var credentials = UserTokenProvider.LoginSilentAsync(clientId, domainName, username, password).Result;
// Create client
SqlManagementClient client = new SqlManagementClient(credentials)
{
SubscriptionId = subscriptionId
};
// Database parameters
var databaseParameters = new Microsoft.Azure.Management.Sql.Models.Database()
{
Location = "ukwest",
ElasticPoolId = elasticPoolId,
};
// Create database
var dbResponse = client.Databases.CreateOrUpdate(resourceGroupName, serverName, databaseName, databaseParameters);
I have found the following SQL script that can be used to create a contained user using SQL management studio but this requires that you manually connect to the database that you want to create the user for:
CREATE USER [databaseUser] WITH PASSWORD = 'xxxxxxxxxxx';
ALTER ROLE [db_datareader] ADD MEMBER [databaseUser]
ALTER ROLE [db_datawriter] ADD MEMBER [databaseUser]
So how can I use the SQL script within my C# code to connect the database after it has been created to then create the contained SQL user for that database, or is there some equivalent code available in Microsoft.Azure.Management.Sql.SqlManagementClient for doing this?
Conceptually, you should think about Azure SQL Database as having (at least) 2 different layers at which you can operate:
There is a REST API for control operations such as creating a database, changing its reservation size, restoring a copy, etc.
There is a T-SQL interface for operations within a database container, from creating tables to inserting rows, etc.
There can be some overlap across these two surfaces - in traditional SQL Server, all of it is exposed in the latter T-SQL interface. Some of those commands are enabled in Azure SQL Database and they are internally calling the REST API for you.
Note that operations to the REST API use the credentials associated with Azure's Portal infrastructure. Within the database, you can have mappings into SQL logins/users, but you can also have SQL logins/users that are not associated at all with the Azure identities.
Net-net: you should connect to the database using the C# SQLClient and run those commands using an authenticated user with enough permissions (in your case, likely the administrator account or sa) to get the new user and role information set up.
Here's a an example on how to set up C# SQLClient

Can't access database, access denied for user

I got this error message while connecting my app with the database at my website.
If i try using XAMPP using my computer, its work well.
FYI, the username and password is same as username and password that i created using XAMPP.
and also grant the privileges.
this is the connection string. for example the server is 174.125.80.140, the database name is myDB, the Uid is alfred, and the password is Alfred111.
MySqlConnection conn = new MySqlConnection("Server=174.125.80.140; Database=myDB;Uid=alfred;Pwd=Alfred111;");
I'm using MySQL client version: 4.1.22.
I'm still can't access the database. is there any solution??
If you are using MySQL workbench,
1) Start the workbench
2) click on the option "Users and Privileges" under SECURITY
3) click on add user (for the specific user), this is more secure because it lets you handle who has access over your database and lets you control access.
however if you want to grant access a large number of users for an application like c# application, then hard-code the username and password in the application, from the user privileges that you have set above.
Hope this helps (^_^)
Yes, you may have supplied the user and password correctly but have you configure the server (new server) to accept Uid=alfred;Pwd=Alfred111;?
Adding User in MySQL Server
If your app is on a different host that the MySQL server then you most likely need to add a new user granting permission for that host. Your alfred user is probably allowed by localhost and nothing else. Try CREATE USER 'altred#'%' identified by 'password'; and then grant that user privileges on myDB.
You can replace % with a specific IP address or hostname as well, % allows the connection from any host which is not necessarily safe.
You can try the following query to see the allowed user/host combos:
SELECT `User`, `Host` FROM `mysql.user`
Hope that helps.

SQL Database Mirroring and your web application

You have two servers when you perform a SQL Server database mirroring
You have 1 primary database and 1 mirror database
Do you need to make any changes to web application to tell it that your using database mirroring? If not how does your web application know which database to use when the primary database fails?
It can be set in the connection string. See the "database mirroring" example here
Do you need to make any changes to web application to tell it that your using database mirroring?
Yes, add the Failover Partner parameter to your connection string, using either the IP or instance name. IE: (line returns for readability)
Data Source = myServerAddress;
Failover Partner = myMirrorServerAddress;
Initial Catalog = myDataBase;
Integrated Security = True;
The mirror doesn't have to exist to test the failover - you can use a dummy address as the Data Source and watched our application use the valid config in the Failover Partner.
But mirroring does not cover logins or jobs - this link provides a script for cloning logins from SQL Server 2005 to other 2005+ instances. You will have to use either ALTER USER or sp_change_users_login to sync the logins if the SIDs are not identical on the principal and mirror.

Remote connect to SQL server - trusted connection, windows credentials

Sorry for the confusing name, I did not know of better one. There is a network with SQL 2005 server. I am provided with the windows account information to this computer so I can use remote desktop or map its drives. The SQL uses trusted connection. I am thinking whether I can connect remotely only to the SQL server? Thanks
This is based on my experience with SQL Server, but may not be entirely complete in scope.
SQL Server Manager will let you connect to the server instance with windows credentials, but to access the database tables you will need to create a login within SQL Server. Using SQL Server Manager, you can do this under the Security folder of the hierarchy of objects in the left column.
Next you will need to create a database (if one doesn't already exist that you are interested in using) and in that database's Security folder, create a user that corresponds to the login. When doing this you will also need to assign the permissions of the user (select, insert, delete, etc.).
Once that is complete, you can access the server anywhere on the network with the appropriate credentials, but you will need to make sure that there are no blocked ports, etc. from a network perspective.
In C# the statement to create a new connection looks like this:
SqlConnection conn = new SqlConnection("user id = username; " +
"password = secret; " +
"server = servername\sqlexpress; " +
"database = databasename; " +
"connection timeout = 30");
Hope that helps.

Categories

Resources