Save win user name by SQL server trigger - c#

There is a local FOX app connected to SQL Server database. There is a trigger in the database which saves changes to the db table like:
INSERT INTO dbo.UpdateContract
SELECT 'OLD' RecordType,USER,SYSTEM_USER,#Time, (...)
I am developing the same app by .NET (C#) and don't know how to use the same trigger to save the name of user who is logged into my .NET app (or windows user).
I can use static cs like
SqlConnection sqlConn = new SqlConnection("Server=servername;Database=dbname;User Id=dbuser;Password=Pass;");
(but, sure, the trigger save this user name and not app user name )
Or this cs:
SqlConnection sqlConn = new SqlConnection("Data Source=servername; Initial Catalog=dbname; Integrated Security=SSPI;");
(but in this case the trigger uses the server machine name)

You can use the SYSTEM_USER function with DEFAULT constraints in the CREATE TABLE and ALTER TABLE statements. You can also use it as any standard function.
If the user name and login name are different, SYSTEM_USER returns the login name.
If the current user is logged in to SQL Server by using Windows Authentication, SYSTEM_USER returns the Windows login identification name in the form: DOMAIN\user_login_name. However, if the current user is logged in to SQL Server by using SQL Server Authentication, SYSTEM_USER returns the SQL Server login identification name, such as WillisJo for a user logged in as WillisJo.
SYSTEM_USER returns the name of the currently executing context. If the EXECUTE AS statement has been used to switch context, SYSTEM_USER returns the name of the impersonated context.
There's a chance that your "non-C# version" is impersonating the context. You can apply this connection after you've connected to server:
EXECUTE AS USER = 'YourWindowsUsername';
that should switch the context. I am not sure if that's the correct approach, you might want to add new field to trigger: CURRENT_USER, this might be something you need.
Source: http://msdn.microsoft.com/en-us/library/ms176050(v=sql.105).aspx

Related

How to add windows user as a SQL users in windows authentication mode

I want to add windows user to SQL users pragmatically. my problem is that I want to do this on systems that have SQL installed in mixed mode but I don't have username and password , I just know the instance name and I don't know how can I execute my script of adding windows user to SQL users in this situation.
I know the script is :
use master
GO
create login [<YourDomain>\User1] from windows;
GO
my connection string is :
ServerConnection myServerConnection = new ServerConnection(myinstancename);
Server myServer = new Server(myServerConnection);
SqlConnection scSqlConnction = new SqlConnection(myServerConnection.ConnectionString);
but when I create a server connection with my instance name, and want to execute script with related connection string I get the error of
login failed for user (windows user)
You Can try this code Must be have UserName in your windows
Windows Login :
CREATE LOGIN [YourDomain\UserName] FROM WINDOWS WITH DEFAULT_DATABASE= master
GO
ALTER SERVER ROLE [sysadmin]
ADD MEMBER [YourDomain\UserName]
GO
SQL Login
CREATE LOGIN UserName
WITH PASSWORD = N'Password'
MUST_CHANGE,
CHECK_POLICY = ON;
GO

.NET SqlClient login failure from background thread in ASP.NET WebForms application

ASP.NET 4.51, WebForms, VS2013
I am using Quartz.NET to do some background processing where ultimately I make a connection to my SQL Server. This all works locally on my development machine against IIS Express, but when I deploy it to my staging server running IIS I run into problems.
The code to connect to the database could not be simpler:
myConnection = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=MyDB;User ID=sa;Password=myPass");
however this throws an exception of:
System.Data.SqlClient.SqlException: Login failed for user 'IIS
APPPOOL\somehost.somedomain.com'.
I am 100% confident the connection string is correct as when used in a normal page it works just fine. So what is throwing me is the reference to IIS APPPOOL.
Is the SqlConnection somehow not using the connection string it was passed? Doing some form of weird user impersonation when the connection is being made?
Put another way. How do I make the SqlConnection() work from within the thread when I know the connection string is correct?
try Application Pool --> Advanced Settings
NetworkServices
Looks like it's failing trying to open a connection to SQL Server.
You need to add a login to SQL Server for IIS APPPOOL\ASP.NET v4.0 and grant permissions to the database.
In SSMS, under the server, expand Security, then right click Logins and select "New Login...".
In the New Login dialog, enter the app pool as the login name and click "OK"
You can then right click the login for the app pool, select Properties and select "User Mapping". Check the appropriate database, and the appropriate roles. I think you could just select db_datareader and db_datawriter, but I think you would still need to grant permissions to execute stored procedures if you do that through EF. You can check the details for the roles here
Refrance : By jeff-ogata
Try setting Integrated Security to false in your connection string. That should prevent it from trying to use Windows authentication.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx
Since you supplied the user id and password, you need to set the "Integrated Security=False" to the connection string. By doing so, it will not use the Application Pool user to connect to the database. For example:
myConnection = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=MyDB;Integrated Security=False;User ID=sa;Password=myPass");

Correct Connection string for accessing remote database server

I have developed a c# program I want to use to access a remote server from a client computer on the same domain.Every time I try to connect to the database I am getting an error login failed for user domain\myclientusername
Using the connection string below:
<add name="dbname" connectionString="Server=remoteservername;Database=dbname;Integrated Security=True;"/>
I have already checked and the server is set to allow remote connections. I am able to log on to the server using admin credentials do I need to set the connection string to use admin password and user name to connect to the database? or do I need to add my client profile credentials to the database permissions. Very new to deploying applications.
You will need to set up access to the database for the connecting user/client PC. You sort of "map" a user on the domain to a SQL user or group
Go to SQL management studio> connect to your database> expand databases > expand 'security' and then 'logins'
right click logins and select new login. search for the user of the connecting user/client PC. Then under the "user mapping" tab you can give access to the specific database. it may be best to give "db_owner" at first just to ensure you have the connection. after that, you should limit the access to only what is needed.
you can always check the SQL events log from the SQL machine itself and see what the specific authentication issues may be. go to "Events" in the Administrative tools (which is in control panel) and you can see SQL specific events.
Either you can remove the Integrated Security=True in your connection string and insert the username and password of a Login you create in you SQL Server database to your connection string.
Or, you can create a login for the user under which your c# program is running (yourself - for testing, domain service account under production) to the SQL Server and give it appropriate read/write access.
More information on connection strings: http://www.connectionstrings.com
More information on how to create login in SQL Server : http://msdn.microsoft.com/en-us/library/aa337562.aspx
When you set Integrated Security=True , the current Windows account credentials are used for authentication.
Since you are trying from a different PC than the one that is running the SQL instance it is much likely the acount you are trying to connect with differs from the acount registered to the instance log in.
what you can do is:
Use Integrated Security=sspi and provide the login credentials, e.g:
connectionString="Server=remoteservername;Database=dbname;User id= myUser; Password=myPass;Integrated Security=sspi";
you can also set Integrated Security=false and also provide the credentials, (but the connection won't be using Windows Athentication)

SQL query getting Server name in triggers when using ASP.NET

I have a trigger set on SQL table for Audit Trail purpose.
Here is the trigger code.
ALTER TRIGGER [dbo].[tri_bowzer_UPDATE] ON [dbo].[Bowzer]
For Update
AS
INSERT Table_Audit(TableName, Action, UserName, ComputerName)
SELECT
'bowzer', 'U', suser_sname(), host_name()
It works fine and shows the username and the computer (client) name in Desktop applications. but in ASP.NET applications, I use a common SQL login so that database operations can be performed using this login. I understand that SQL Server is getting server machine name because of this ID. However, I want to capture the client machine name whenever a database operation is performed.
What changes can be made to get client machine name??
You need to tweak your connection string to specify the connectionstring property WSID (Workstation id) as below
string strconn = "data source=SQLSERVER;initial catalog = DBNAME ; uid=sa;pwd=password; WSID=" + (System.Net.Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName);
and then you will get HOST_NAME() value as client machine name in your trigger
MSDN : http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx
You can set the client's IP address using T-SQL SET CONTEXT_INFO, and retrieve this data in the trigger using the CONTEXT_INFO function.
This design is not really suitable for what you are trying to achieve. I'd consider adding updated by column in your database where you can store user id or machine name of a user who updated data.
This way you'll keep the trigger logic simple and avoid too many connections to your database that might degrade performance.

sql server creation of logins and users by another user

I am using SQL Server Express 2005.
I have a single database myDB
I have created a Login L-1 with user U-1 on databas myDB.
To connect to database myDB I found 3 ways:
-1(a)-after creating L-1 Login with default database = myDB , I have to create a user U-1 , and when I connected to SQL server , then it connected.
I used this query:
create login L-1 with password='passL1' , default_database = myDB
use myDB
create user U-1 for login L-1
Means, creating a user inside a login , gives the user connect permission implicitly. Am I right ?
-1(b)-I didn't create any user U-1, but executed this :
use myDB
sp_grantdbaccess L-1
this also made me connect , the reason being that, sql added a user named L-1 implicitly in the myDB database. Am I right?
-1(c)-this time also, I didn't create any user U-1,but I executed this:
sp_changedbowner L-1
this also made me connect , the reason being that, sql added a user named L-1 implicitly in the myDB database. Am I right?
Now, I want to give the user U-1 created in 1(a) the following permissions:
Create Logins L-2,L-3
Create Users U2,U3 which can also connect to database myDB.
How do I do this?
Yes - calling sp_grantdbaccess or sp_changedbowner will just implicitly do what you would normally do with CREATE USER - no difference.
Calling CREATE USER explicitly is just clearer, more obvious what you're doing etc.
Also: don't use sp_grantdbaccess anymore - because:
This feature will be removed in a
future version of Microsoft SQL
Server. Avoid using this feature in
new development work, and plan to
modify applications that currently use
this feature. Use CREATE USER instead.
Source: Technet on sp_Grantdbaccess
And don't use sp_changedbowner either - same reason:
This feature will be removed in a
future version of Microsoft SQL
Server. Avoid using this feature in
new development work, and plan to
modify applications that currently use
this feature. Use ALTER AUTHORIZATION
instead.
Source: Technet on sp_changedbower

Categories