SqlConnection.AccessTokenCallback 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得或設定連接的存取令牌回呼。
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 並傳回的 SqlAuthenticationTokenFunc。
例外狀況
AccessTokenCallback 會與其他衝突的驗證組態結合。
範例
下列範例示範如何定義和設定 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);
}
}
}