언어

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

속성 값

를 사용하고 SqlAuthenticationParametersCancellationToken 반환하는 Func입니다 SqlAuthenticationToken.

예외

충돌 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가 있는 경우 동일한 콜백 함수는 항상 동일한 보안 컨텍스트의 유효한 액세스 토큰을 제공해야 합니다. 여러 연결이 동일한 콜백 함수를 사용하고 풀 키를 구성하는 다른 모든 속성이 동일한 경우 동일한 연결 풀로 그룹화됩니다.

드라이버는 토큰 새로 고침을 관리하고 다시 사용하기 전에 만료되었거나 거의 만료된 토큰이 있는 풀된 연결을 삭제합니다. 동일한 활성 트랜잭션 내에서 사용 중이거나 다시 사용하는 연결은 영향을 받지 않습니다.

새 물리적 연결은 캐시된 토큰이 없거나 새로 고쳐야 하는 경우에만 콜백을 호출합니다. 풀링된 연결을 다시 사용하는 경우 콜백이 호출되지 않습니다.

이 속성은 다른 속성과 SspiContextProvider 함께 사용할 수 없습니다AccessToken. SSPI는 토큰 기반 인증의 InvalidOperationException대안이기 때문에 이미 설정된 경우 SspiContextProvider 이 속성을 설정하면 throw됩니다.

적용 대상