Search code examples
c#access-tokenservice-principal

LinqToDB How to add AccessToken to database connection


I need to use ServicePrincipal to authenticate to SQL server using LinqToDB. I followed this microsoft article to test that the setup is correct. However this example uses System.Data.Sqlclient.SqlConnection class that has an AccessToken property so it can add the AccessToken to the connection.

using (var conn = new SqlConnection(sqlConnectionString))
{
    conn.AccessToken = authenticationResult.AccessToken;
    // ...
}

I am using LinqToDB and trying to figure out where can I add the AccessToken obtained from AD. The DataConnection (source) does not have an AccessToken property.


Solution

  • In case someone is interested here is the solution.

    1. Create a connection factory class, adding the Access Token in the connection object, like so:

      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;
      }
      
    2. create a data provider for your database:

          IDataProvider MyDataProvider = new SqlServerDataProvider("SqlServer", SqlServerVersion.v2008);
      
    3. Pass these into the constructor for DataConnection

    using (var db = new DataConnection(MyDataProvider, MyConnectionFactory))