Skip to content

Commit

Permalink
Improve AccessTokenCallback sample code (#2543)
Browse files Browse the repository at this point in the history
  • Loading branch information
scottaddie authored May 31, 2024
1 parent 42e9f08 commit 348ae2e
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions doc/samples/SqlConnection_AccessTokenCallback.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,21 @@ static void Main()

private static void OpenSqlConnection()
{
const string defaultScopeSuffix = "/.default";
string connectionString = GetConnectionString();
using (SqlConnection connection = new SqlConnection("Data Source=contoso.database.windows.net;Initial Catalog=AdventureWorks;")
DefaultAzureCredential credential = new();

using (SqlConnection connection = new(connectionString)
{
AccessTokenCallback = async (authParams, cancellationToken) =>
{
var cred = new DefaultAzureCredential();
string scope = authParams.Resource.EndsWith(s_defaultScopeSuffix) ? authParams.Resource : authParams.Resource + s_defaultScopeSuffix;
var token = await cred.GetTokenAsync(new TokenRequestContext(new[] { scope }), cancellationToken);
string scope = authParams.Resource.EndsWith(defaultScopeSuffix)
? authParams.Resource
: $"{authParams.Resource}{defaultScopeSuffix}";
AccessToken token = await credential.GetTokenAsync(
new TokenRequestContext([scope]),
cancellationToken);
return new SqlAuthenticationToken(token.Token, token.ExpiresOn);
}
})
Expand Down

0 comments on commit 348ae2e

Please sign in to comment.