gpt4 book ai didi

c# - 在不使用用户 ID 和密码的情况下对 Azure SQL 数据库进行身份验证

转载 作者:行者123 更新时间:2023-12-04 17:31:12 30 4
gpt4 key购买 nike

我正在尝试使用此代码通过 C# 对我的 Azure SQL 进行身份验证。该代码有效,但我不想使用我的用户 ID 和密码。我可以使用其他任何东西进行身份验证吗? token ?

using System;
using System.Data.SqlClient;
using System.Text;

namespace sqltest
{
class Program
{
static void Main(string[] args)
{
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "<server>.database.windows.net";
builder.UserID = "<username>";
builder.Password = "<password>";
builder.InitialCatalog = "<database>";

using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
Console.WriteLine("\nQuery data example:");
Console.WriteLine("=========================================\n");

StringBuilder sb = new StringBuilder();
sb.Append("SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName ");
sb.Append("FROM [SalesLT].[ProductCategory] pc ");
sb.Append("JOIN [SalesLT].[Product] p ");
sb.Append("ON pc.productcategoryid = p.productcategoryid;");
String sql = sb.ToString();

using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1}", reader.GetString(0), reader.GetString(1));
}
}
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
}
}

最佳答案

你可以使用 2 个东西。
1. 为 Azure 资源使用托管身份
这是推荐的方法,在此方法中,代码将使用 azure identities 生成 token 。

.NET Framework 4.6 or higher or .NET Core 2.2 or higher is required to use the access token method.

更多信息-> https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-windows-vm-access-sql

2.将敏感信息(用户名/密码/连接字符串)存储在azure key vault中
https://learn.microsoft.com/en-us/azure/key-vault/tutorial-net-create-vault-azure-web-app

关于c# - 在不使用用户 ID 和密码的情况下对 Azure SQL 数据库进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59549185/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com