azure 当< token-identified principal>用户在AAD组中时,用户“”登录失败

cbjzeqam  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(95)

目前,我是添加到Azure Active Directory中的用户。我尝试在.Net C#中使用visualstudio凭据登录,但出现错误。用户'token-identified principal'登录失败我可以使用SSMS和Azure MFA登录到数据库。
C#代码。

public async Task<SqlConnection> GetAzureSqlAccessTokenAsync(
        AzureSqlConnectionOptions azureSqlConnectionOptions,
        CancellationToken cancellationToken = default)
    {
        
        var connectionStringBuilder = GetConnectionString(azureSqlConnectionOptions);
        var sqlConnection = new SqlConnection(connectionStringBuilder.ConnectionString);
        
        var tokenRequestContext = new TokenRequestContext(_azureSqlScopes);

        var chainedTokenCredential = new ChainedTokenCredential(
                                        //new ManagedIdentityCredential(),
                                        new VisualStudioCredential(),
                                        new VisualStudioCodeCredential(),
                                        new AzureCliCredential()
                                        );

        var token = await chainedTokenCredential.GetTokenAsync(tokenRequestContext, cancellationToken);
            sqlConnection.AccessToken = token;
        
        try
        {
            // sanity test
            await sqlConnection.OpenAsync(); // fails here
            var sqlCommand = new SqlCommand("SELECT GETDATE()", sqlConnection);
            var currentTime = await sqlCommand.ExecuteScalarAsync(cancellationToken);
        }
        catch(Exception e)
        {
            var ex = e.InnerException;
        }
        return sqlConnection;
    }
toe95027

toe950271#

使用下面的**c#**代码,我可以登录到Azure Active Directory身份验证。

ConnectionString:

"ConnectionStrings": {
    "QuotesDatabase": "Server=tcp:servename.database.windows.net,1433; Database=databasename;" }

验证码:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration.GetConnectionString("QuotesDatabase");
            services.AddTransient(a =>
            {
                var sqlConnection = new SqlConnection(connectionString);
                var credential = new DefaultAzureCredential();
                var token = credential
                        .GetToken(new Azure.Core.TokenRequestContext(
                            new[] { "https://database.windows.net/.default" }));
                sqlConnection.AccessToken = token.Token;
                return sqlConnection;
            });
                services.AddControllers();
        }   
}

我设置azure服务身份验证来检索令牌凭据。

输出:

相关问题