entity-framework - 使用访问 token 连接到 SQL Azure DB 的 Entity Framework

标签 entity-framework azure-active-directory adal

我们有连接到 SQL Azure DB 的 Web 应用程序。我已经使用应用程序 ID 和证书配置了我的应用程序。我们想使用访问 token 方法连接到 SQL Server,根据下面的链接,通过 token 方法连接到 SQL Server 不是一种可靠的方法。任何推荐的连接方式,而不是用户 ID 和密码。

Connect to Azure SQL using Azure Active Directory from an Azure Website?

任何人都可以让我知道他们是否已经使用 Entity Framework 实现了基于 SQL Azure DB AAD token 的身份验证,并且这是正确的连接方式。

最佳答案

根据你的描述,我关注了tutorial关于对 Azure SQL 数据库使用 AAD 身份验证。

像这样tutorial提到了 Azure AD token 身份验证 :

This authentication method allows middle-tier services to connect to Azure SQL Database or Azure SQL Data Warehouse by obtaining a token from Azure Active Directory (AAD). It enables sophisticated scenarios including certificate-based authentication.You must complete four basic steps to use Azure AD token authentication:

  • Register your application with Azure Active Directory and get the client id for your code.
  • Create a database user representing the application. (Completed earlier in step 6.)
  • Create a certificate on the client computer runs the application.
  • Add the certificate as a key for your application.


然后我关注了code sample在此 blog开始使用此功能,它按预期工作。

Can anyone let me know if they have implemented SQL Azure DB AAD token based authentication using entity framework and is it right way for connecting.



基于上面的代码示例,我添加了 EntityFramework 6.1.3用于使用 Entity Framework 实现基于 SQL Azure DB AAD token 的身份验证。经过一些试验,我可以让它按预期工作。这里有一些细节,你可以引用。

数据库上下文
public class BruceDbContext : DbContext
{
    public BruceDbContext()
        : base("name=defaultConnectionString")
    { }

    public BruceDbContext(SqlConnection con) : base(con, true)
    {
        Database.SetInitializer<BruceDbContext>(null);
    }

    public virtual DbSet<User> Users { get; set; }
}

数据模型
[Table("Users")]
public class User
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    [StringLength(50)]
    public string UserName { get; set; }
    public DateTime CreateTime { get; set; }
}

程序.cs
class Program
{
    static void Main()
    {
        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
        builder["Data Source"] = "brucesqlserver.database.windows.net";
        builder["Initial Catalog"] = "brucedb";
        builder["Connect Timeout"] = 30;

        string accessToken = TokenFactory.GetAccessToken();
        if (accessToken == null)
        {
            Console.WriteLine("Fail to acuire the token to the database.");
        }
        using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
        {
            try
            {   
                connection.AccessToken = accessToken;
                //working with EF
                using (var model = new BruceDbContext(connection))
                {
                   var users= model.Users.ToList();
                    Console.WriteLine($"Results:{Environment.NewLine}{JsonConvert.SerializeObject(users)}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        Console.WriteLine("Please press any key to stop");
        Console.ReadKey();
    }
}

结果

enter image description here

注:通过 CREATE USER [mytokentest] FROM EXTERNAL PROVIDER 为您的应用程序主体包含的数据库用户没有任何权限访问您的数据库。您需要为此用户授予权限,更多详细信息您可以引用此 issue .

此外,当您构造 DbContext 时例如,您需要实现 SqlConnection具有有效 AccessToken 的实例. AFAIK,您需要在 token 过期时处理 token 刷新。

关于entity-framework - 使用访问 token 连接到 SQL Azure DB 的 Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43130105/

相关文章:

c# - ASP.NET Core、Microsoft 帐户登录和 AADSTS70001

c# - 在 ASP.NET Core 2.0 中将 Azure Active Directory OAuth 与身份模型结合使用

angularjs - 当您必须登录时,Azure Active Directory (ADAL) 不会将您重定向到您尝试打开的页面

c# - Entity Framework 代码优先 : Using a database that doesn't need to be separately installed?

c# - 跳过/采用两个合并列表的策略

c# - 无需 PredicateBuilder 将动态谓词添加到表达式

c# - Entity Framework 并不总是包括子实体

azure - 无法使用服务主体创建映射到 Azure AD 标识的 Azure SQL 数据库用户

javascript - 无法读取用户信息 - Adal 错误无法登录

java - Microsoft Graph 401 未经授权使用访问 token