[英]Good ways to pass user name from C# native app to SQL Server via a web service running under a service account
Our company has a model where all Web services run under its own specific service account. 我们公司有一个模型,其中所有Web服务都在其自己的特定服务帐户下运行。 for example: comp\\Ws.App
例如:comp \\ Ws.App
This Web service does all the Database interaction using Store procedures to a SQL database and the service account has all the rights to do so. 该Web服务使用存储过程对SQL数据库执行所有数据库交互,并且该服务帐户具有这样做的所有权利。
We have a native client built written in C# that uses the web service for all data related queries. 我们有一个用C#编写的本地客户端,该客户端使用Web服务进行所有与数据相关的查询。
My problem is that we have audits on these database tables using triggers which record the user using the USER_NAME() build in SQl function. 我的问题是,我们使用触发器对这些数据库表进行审核,这些触发器使用SQl函数中内置的USER_NAME()记录用户。
Is there any way that the name of the user running the Native app gets passed in to a SQL build in function? 运行本机应用程序的用户名是否可以通过任何方式传递给SQL内置函数? It does not have to be the USER_NAME() function, but any built in function is good enough.
它不必是USER_NAME()函数,但是任何内置函数都足够。
What I am trying to avoid is the following: 我想避免的是以下情况:
Currently what I do is change the Application Name property in the SQL connection string to include the user identity and strip this from the APP_NAME() built in SQL function 当前,我要做的是更改SQL连接字符串中的“ 应用程序名称”属性以包括用户身份,并将其从SQL函数内置的APP_NAME()中删除
Notes 笔记
Any other good solutions? 还有其他好的解决方案吗?
One option is to store the user id in the SQL Server context info. 一种选择是将用户ID存储在SQL Server上下文信息中。 As soon as the web service identifies or authenticates the user, then the web service stores the user id in the context info, this can be done by calling a stored procedure like the following:
一旦Web服务标识或认证了用户,然后Web服务便将用户ID存储在上下文信息中,这可以通过调用如下存储过程来完成:
CREATE PROCEDURE SetUserContext
@UserId int
AS
DECLARE @uc binary(4)
SET @uc = CONVERT(binary(4), @UserId)
SET CONTEXT_INFO @ci
Then, audit trail triggers read the user id from the context info using a code like this one: 然后,审核跟踪触发器使用如下代码从上下文信息中读取用户ID:
DECLARE @UserId int
SET @UserId = CONVERT(int, SUBSTRING(CONTEXT_INFO(), 1, 4))
Of course you need to keep the connection open after calling SetUserContext, if you close the connection the context info is lost. 当然,您需要在调用SetUserContext之后保持连接打开,如果关闭连接,则上下文信息将丢失。 So the sequence of actions should be as follows:
因此,操作顺序应如下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.