![](/img/trans.png)
[英]Accessing on-premises SQL database with web application hosted on Azure
[英]Azure SQL Database Application
我正在構建需要SQL數據庫的桌面應用程序。 我希望為客戶提供2種選擇:本地和雲數據庫。 對於雲數據庫,我打算使用Azure SQL服務器。 要求是:
我的問題是,在測試中,我遇到了“不允許IP地址連接到服務器”的問題。 這帶來了一個問題:
聽起來聽起來很奇怪,但我找不到解決該問題的即用型解決方案。 我是一個新程序員,也許谷歌還不夠用……也就是說,這似乎是一個簡單的問題,沒有一個簡單的明顯解決方案。
我想出的最好的解決方案是應用程序中的嵌入式Open-VPN Client。 但是,這似乎不必要地復雜。 有沒有更好的辦法?
為簡化起見,在您的應用程序上使用基於令牌的身份驗證。
public async Task<string> GetAccessTokenAsync(string clientId, string clientSecret, string authority, string resource, string scope)
{
var authContext = new AuthenticationContext(authority, TokenCache.DefaultShared);
var clientCred = new ClientCredential(clientId, clientSecret);
var result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
{
throw new InvalidOperationException("Could not get token");
}
return result.AccessToken;
}
使用令牌創建SQL連接。
public async Task<SqlConnection> GetSqlConnectionAsync(string tenantId, string clientId, string clientSecret, string dbServer, string dbName)
{
var authority = string.Format("https://login.windows.net/{0}", tenantId);
var resource = "https://database.windows.net/";
var scope = "";
var token = await GetTokenAsync(clientId, clientSecret, authority, resource, scope);
var builder = new SqlConnectionStringBuilder();
builder["Data Source"] = $"{dbServer}.database.windows.net";
builder["Initial Catalog"] = dbName;
builder["Connect Timeout"] = 30;
builder["Persist Security Info"] = false;
builder["TrustServerCertificate"] = false;
builder["Encrypt"] = true;
builder["MultipleActiveResultSets"] = false;
var con = new SqlConnection(builder.ToString());
con.AccessToken = token;
return con;
}
您甚至不必擔心令牌到期,因為AzureServiceTokenProvider負責緩存。
了解它的這個文章。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.