dotnet / dotnet/efcore

How to handle Microsoft.Data.SqlClient new AccessTokenCallback

Open
#33,205 5 comments 1 reaction 0 assignees View on GitHub
area-dbcontext customer-reported needs-design
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

In version 5.2.0 of Microsoft.Data.SqlClient a new callback was added to the SqlConnection class in order to retrieve an access token. What is the best place to set this property. I don’t think it’s necessary to set it on each execution of the IDbConnection interceptor like I did before with the AccessToken property, right?

More info on the new functionality [here](https://github.com/dotnet/SqlClient/pull/1260).

Previous:
```c#
public override async ValueTask ConnectionOpeningAsync(DbConnection connection, ConnectionEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default)
{
var sqlConnection = (SqlConnection)connection;
var accessToken = await _credential.GetTokenAsync(AzureSqlScope, cancellationToken: cancellationToken);

sqlConnection.AccessToken = accessToken.Token;

return ValueTask.FromResult(result);
}
```

New:
```c#
private readonly Func> _accessTokenCallback;

public AzureAdAuthenticationDbConnectionInterceptor()
{
_accessTokenCallback = AccessTokenCallback;
}

public override ValueTask ConnectionOpeningAsync(DbConnection connection, ConnectionEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default)
{
if (connection is SqlConnection sqlConnection && sqlConnection.AccessTokenCallback is null)
{
sqlConnection.AccessTokenCallback = _accessTokenCallback;
}

return ValueTask.FromResult(result);
}

private async Task AccessTokenCallback(SqlAuthenticationParameters sqlAuthenticationParameters, CancellationToken cancellationToken)
{
var accessToken = await _credential.GetTokenAsync(AzureSqlScope, cancellationToken: cancellationToken);

return new SqlAuthenticationToken(accessToken.Token, accessToken.ExpiresOn);
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.