Language

SqlConnection.AccessTokenCallback プロパティ

定義

接続のアクセス トークン コールバックを取得または設定します。

public:
 property Func<Microsoft::Data::SqlClient::SqlAuthenticationParameters ^, System::Threading::CancellationToken, System::Threading::Tasks::Task<Microsoft::Data::SqlClient::SqlAuthenticationToken ^> ^> ^ AccessTokenCallback { Func<Microsoft::Data::SqlClient::SqlAuthenticationParameters ^, System::Threading::CancellationToken, System::Threading::Tasks::Task<Microsoft::Data::SqlClient::SqlAuthenticationToken ^> ^> ^ get(); void set(Func<Microsoft::Data::SqlClient::SqlAuthenticationParameters ^, System::Threading::CancellationToken, System::Threading::Tasks::Task<Microsoft::Data::SqlClient::SqlAuthenticationToken ^> ^> ^ value); };
public Func<Microsoft.Data.SqlClient.SqlAuthenticationParameters,System.Threading.CancellationToken,System.Threading.Tasks.Task<Microsoft.Data.SqlClient.SqlAuthenticationToken>> AccessTokenCallback { get; set; }
member this.AccessTokenCallback : Func<Microsoft.Data.SqlClient.SqlAuthenticationParameters, System.Threading.CancellationToken, System.Threading.Tasks.Task<Microsoft.Data.SqlClient.SqlAuthenticationToken>> with get, set
Public Property AccessTokenCallback As Func(Of SqlAuthenticationParameters, CancellationToken, Task(Of SqlAuthenticationToken))

プロパティ値

SqlAuthenticationParametersとCancellationTokenを受け取り、SqlAuthenticationTokenを返す Func。

例外

AccessTokenCallbackは、他の競合する認証構成と組み合わされます。

例

次の例では、 AccessTokenCallbackを定義および設定する方法を示します。

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Microsoft.Data.SqlClient;

class Program
{
    static void Main()
    {
        OpenSqlConnection();
        Console.ReadLine();
    }

    const string defaultScopeSuffix = "/.default";

    // Reuse credential objects to take advantage of underlying token caches.
    private static ConcurrentDictionar<string, DefaultAzureCredential> credentials = new ConcurrentDictionary<string, DefaultAzureCredential>();

    // Use a shared callback function for connections that should be in the same connection pool.
    private static Func<SqlAuthenticationParameters, CancellationToken, Task<SqlAuthenticationToken>> myAccessTokenCallback =
        async (authParams, cancellationToken) =>
        {
            string scope = authParams.Resource.EndsWith(defaultScopeSuffix)
                ? authParams.Resource
                : $"{authParams.Resource}{defaultScopeSuffix}";

            DefaultAzureCredentialOptions options = new DefaultAzureCredentialOptions();
            options.ManagedIdentityClientId = authParams.UserId;

            // Reuse the same credential object if we are using the same MI Client ID.
            AccessToken token = await credentials.GetOrAdd(authParams.UserId, new DefaultAzureCredential(options)).GetTokenAsync(
                new TokenRequestContext(new string[] { scope }),
                cancellationToken);

            return new SqlAuthenticationToken(token.Token, token.ExpiresOn);
        };

    private static void OpenSqlConnection()
    {
        // (Optional) Pass a User-Assigned Managed Identity Client ID.
        // This will ensure different MI Client IDs are in different connection pools.
        string connectionString = "Server=myServer.database.windows.net;Encrypt=Mandatory;UserId=<ManagedIdentityClientId>;";

        using (SqlConnection connection = new SqlConnection(connectionString)
        {
            // The callback function is part of the connection pool key. Using a static callback function
            // ensures connections will not create a new pool per connection just for the callback.
            AccessTokenCallback = myAccessTokenCallback
        })
        {
            connection.Open();
            Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
            Console.WriteLine("State: {0}", connection.State);
        }
    }
}

注釈

AccessTokenCallback 関数自体は、接続プール キーの一部です。 同じコールバック関数は、同じ SqlAuthenticationParameters を指定すると、常に同じセキュリティ コンテキストの有効なアクセス トークンを提供する必要があります。 複数の接続が同じコールバック関数を使用し、プール キーを構成する他のすべてのプロパティが同じである場合、それらは同じ接続プールにグループ化されます。

ドライバーは、トークンの更新を管理し、再利用する前に、期限切れまたはほぼ期限切れのトークンを使用してプールされた接続を破棄します。 同じアクティブなトランザクション内で使用中または再利用されている接続は影響を受けません。

新しい物理接続は、キャッシュされたトークンが見つからないか、更新が必要な場合にのみコールバックを呼び出します。 プールされた接続を再利用しても、コールバックは呼び出されません。

このプロパティは、 AccessToken プロパティや SspiContextProvider プロパティと相互に排他的です。 SspiContextProviderが既に設定されている場合にこのプロパティを設定すると、InvalidOperationExceptionがスローされます。SSPI はトークン ベースの認証の代わりに使用されるためです。

適用対象