【问题标题】:LinqToDB How to add AccessToken to database connectionLinqToDB 如何将 AccessToken 添加到数据库连接
【发布时间】:2019-07-28 08:36:37
【问题描述】:
我需要使用ServicePrincipal 来使用LinqToDB 对SQL Server 进行身份验证。我跟着this microsoft article 测试设置是否正确。但是,此示例使用具有 AccessToken 属性的 System.Data.Sqlclient.SqlConnection 类,因此它可以将 AccessToken 添加到连接中。
using (var conn = new SqlConnection(sqlConnectionString))
{
conn.AccessToken = authenticationResult.AccessToken;
// ...
}
我正在使用LinqToDB 并试图找出在哪里可以添加从AD 获得的AccessToken。 DataConnection (source) 没有 AccessToken 属性。
【问题讨论】:
标签:
c#
access-token
service-principal
【解决方案1】:
如果有人对这里感兴趣,那就是解决方案。
-
创建一个连接工厂类,在连接对象中添加Access Token,如下:
public IDbConnection MyConnectionFactory()
{
ClientCredential clientCredential = new ClientCredential(ClientId,ClientSecret);
AuthenticationContext authenticationContext = new AuthenticationContext(AuthorityUrl);
AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(TargetUrl, clientCredential).Result;
SqlConnection MyDataConnection = new SqlConnection(ConnectionString);
MyDataConnection.AccessToken = authenticationResult.AccessToken;
return MyDataConnection;
}
-
为您的数据库创建数据提供者:
IDataProvider MyDataProvider = new SqlServerDataProvider("SqlServer", SqlServerVersion.v2008);
将这些传递给 DataConnection 的构造函数
using (var db = new DataConnection(MyDataProvider, MyConnectionFactory))