SqlConnection.AccessTokenCallback Proprietà
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
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
viene AccessTokenCallback combinato con altre configurazioni di autenticazione in conflitto.
Esempio
Nell'esempio seguente viene illustrato come definire e impostare un oggetto 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);
}
}
}
Commenti
La funzione AccessTokenCallback stessa fa parte della chiave del pool di connessioni. La stessa funzione di callback deve sempre fornire un token di accesso valido dello stesso contesto di sicurezza dato lo stesso SqlAuthenticationParameters. Quando più connessioni usano la stessa funzione di callback e tutte le altre proprietà che costituiscono la chiave del pool sono uguali, verranno raggruppate nello stesso pool di connessioni.
Il driver gestisce l'aggiornamento del token e rimuove le connessioni in pool con token scaduti o quasi scaduti prima del riutilizzo. Le connessioni in uso o riutilizzate all'interno della stessa transazione attiva non sono interessate.
Le nuove connessioni fisiche richiamano il callback solo quando manca un token memorizzato nella cache o richiede l'aggiornamento. Il riutilizzo di una connessione in pool non richiama il callback.
Questa proprietà si escludono a vicenda con le AccessToken proprietà e SspiContextProvider , tra le altre. L'impostazione di questa proprietà quando SspiContextProvider è già impostata genera InvalidOperationException, perché SSPI è un'alternativa all'autenticazione basata su token.