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.
In case someone is interested here is the solution.
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;
}
create a data provider for your database:
IDataProvider MyDataProvider = new SqlServerDataProvider("SqlServer", SqlServerVersion.v2008);
Pass these into the constructor for DataConnection
using (var db = new DataConnection(MyDataProvider, MyConnectionFactory))