Share via


SqlConnection.AccessTokenCallback Proprietà

Definizione

Ottiene o imposta il callback del token di accesso per la connessione.

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

Valore della proprietà

Func che accetta e SqlAuthenticationParametersCancellationToken restituisce un oggetto SqlAuthenticationToken.

Eccezioni

AccessTokenCallback viene combinato con altre configurazioni di autenticazione in conflitto.

Esempio

Nell'esempio seguente viene illustrato come definire e impostare un oggetto AccessTokenCallback.

using Microsoft.Data.SqlClient;
using Azure.Identity;

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

    private static void OpenSqlConnection()
    {
        string connectionString = GetConnectionString();
        using (SqlConnection connection = new SqlConnection("Data Source=contoso.database.windows.net;Initial Catalog=AdventureWorks;")
        {
            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);
                return new SqlAuthenticationToken(token.Token, token.ExpiresOn);
            }
        })
        {
            connection.Open();
            Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
            Console.WriteLine("State: {0}", connection.State);
        }
    }
}

Si applica a