【问题标题】:Asp.Net read/write to Azure data lake and Azure SQL ServerAsp.Net 读取/写入 Azure 数据湖和 Azure SQL Server
【发布时间】:2019-06-11 22:07:41
【问题描述】:

我喜欢创建 Web 应用来上传文件、保存到 azure 数据湖、读/写到 azure SQL Server。

我使用我的 Azure AD clientId/secret 来访问数据湖,

我的 Azure SQL Server 连接字符串,例如:Server=tcp:{MyAzureSQLServer}.database.windows.net,1433;Initial Catalog={MyAzureDatabase};Persist Security Info=False;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate= False;Authentication="Active Directory 集成"

Asp.Net Mvc Core,数据湖工作正常,但 Azure SQL 报告:不支持关键字:“身份验证”。

Asp.Net Mvc (Framework),Azure SQL 工作,但是数据湖报告错误:'Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache' 的类型初始化器抛出异常。

我做错了什么?

谢谢, 韦斯

【问题讨论】:

    标签: asp.net azure azure-active-directory azure-sql-database azure-data-lake


    【解决方案1】:

    使用访问令牌(通过托管身份获得)在用于 .NET Core 的 SQL 客户端中使用 Azure Active Directory 身份验证。下面是您需要的所有内容,包括连接字符串。

    Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        //code ignored for simplicity
        services.AddDbContext<MyCustomDBContext>();
    
        services.AddTransient<IDBAuthTokenService, AzureSqlAuthTokenService>();
    }
    

    MyCustomDBContext.cs

    public partial class MyCustomDBContext : DbContext
    {
        public IConfiguration Configuration { get; }
        public IDBAuthTokenService authTokenService { get; set; }
    
        public CortexContext(IConfiguration configuration, IDBAuthTokenService tokenService, DbContextOptions<MyCustomDBContext> options)
            : base(options)
        {
            Configuration = configuration;
            authTokenService = tokenService;
        }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            SqlConnection connection = new SqlConnection();
            connection.ConnectionString = Configuration.GetConnectionString("defaultConnection");
            connection.AccessToken = authTokenService.GetToken().Result;
    
            optionsBuilder.UseSqlServer(connection);
        }
    }
    

    AzureSqlAuthTokenService.cs

    public class AzureSqlAuthTokenService : IDBAuthTokenService
    {
        public async Task<string> GetToken()
        {
            AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
            var token = await provider.GetAccessTokenAsync("https://database.windows.net/");
    
            return token;
        }
    }
    

    有关使用访问令牌 here 的 AAD 身份验证的更多信息。

    【讨论】:

    • 谢谢你,Alberto,我认为这是针对 Asp.Net Mvc Core 的,对吗?
    • .NET Core 和 EF Core
    • 嗨@AlbertoMorillo 您能否指定哪个 Nuget 包或命名空间已用于 IDBAuthTokenService。谢谢
    • @Deepak 他用的是这个:Microsoft.Azure.Services.AppAuthentication
    • @Maturano 感谢您的回复,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 2017-11-18
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多