Język

SqlConnection.AccessTokenCallback Właściwość

Definicja

Pobiera lub ustawia wywołanie zwrotne tokenu dostępu dla połączenia.

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))

Wartość właściwości

Func, który przyjmuje SqlAuthenticationParameters element i CancellationToken i zwraca wartość SqlAuthenticationToken.

Wyjątki

Element AccessTokenCallback jest połączony z innymi konfiguracjami uwierzytelniania powodującego konflikt.

Przykłady

W poniższym przykładzie pokazano, jak zdefiniować i ustawić element 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);
        }
    }
}

Uwagi

Sama funkcja AccessTokenCallback jest częścią klucza puli połączeń. Ta sama funkcja wywołania zwrotnego powinna zawsze zapewniać prawidłowy token dostępu tego samego kontekstu zabezpieczeń, biorąc pod uwagę te same parametry SqlAuthenticationParameters. Jeśli wiele połączeń używa tej samej funkcji wywołania zwrotnego, a wszystkie inne właściwości składające się na klucz puli są takie same, zostaną zgrupowane w tej samej puli połączeń.

Sterownik zarządza odświeżaniem tokenu i odrzuca połączenia w puli z wygasłymi lub prawie wygasłymi tokenami przed ponownym użyciem. Nie ma to wpływu na połączenia używane lub ponownie używane w ramach tej samej aktywnej transakcji.

Nowe połączenia fizyczne wywołują wywołanie zwrotne tylko wtedy, gdy brakuje buforowanego tokenu lub wymaga odświeżenia. Ponowne użycie połączenia w puli nie wywołuje wywołania zwrotnego.

Ta właściwość wyklucza się wzajemnie z właściwościami AccessToken i SspiContextProvider , między innymi. Ustawienie tej właściwości, gdy SspiContextProvider jest już ustawiona InvalidOperationExceptionzgłasza wyjątek , ponieważ SSPI jest alternatywą dla uwierzytelniania opartego na tokenach.

Dotyczy