I am building a desktop application that requires a SQL Database. I wish to offer clients 2 options: On Premises and Cloud database. For cloud databases I intend to use azure sql server. The requirements are:
My problem is, in testing I have run into the "IP Address not allowed to connect to server". This poses a problem:
As bizarre as this sounds, I cannot find a ready-to-use solution to this problem. I am a new programmer, and maybe have not googled enough... That being said, this seems like a simple problem without a simple obvious solution.
The best solution I have come up with is an embedded Open-VPN Client within the application. However, that seems unnecessarily complicated. Is there a better way?
Use token-based authentication on your application for simplicity.
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;
}
Creating a SQL Connection using token.
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;
}
You don't even need to worry about token expiration since AzureServiceTokenProvider takes care of caching.
Learn about it on this article.
Did you think about the Azure firewall? To add the client IP or IP address range to limit the access of Azure SQL database.
Set server firewall on portal:
Firewall settings: to add the client IP or IP address range to provides the access the database.
Fore more details, please see:
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.