托管标识和SQL连接 [英] Managed Identity and SQL connection

查看:60
本文介绍了托管标识和SQL连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我们有一个AppService是一个带有IdentityServer4组件的令牌服务。此应用程序服务部署到Azure并具有托管标识。这工作正常,但在9个小时后,令牌已经过期(并且没有续订),突然
应用程序不再连接到SQL数据库了。

we have an AppService being a tokenservice with IdentityServer4 components. This appservice is deployed to Azure and has a managed identity. This works fine but after exactly 9 hours somehow the token is expired (and not getting renewed) and suddenly the app is not connecting to the SQL database anymore.

这是怎么回事我们设置了IdentityServer4管道。

This is how we setup the IdentityServer4 plumbing.

var identityServer = services.AddIdentityServer(options =>
    {
        options.Events.RaiseErrorEvents = true;
        options.Events.RaiseInformationEvents = true;
        options.Events.RaiseFailureEvents = true;
        options.Events.RaiseSuccessEvents = true;
    })

    // this adds the config data from DB (clients, resources, CORS)
    .AddConfigurationStore(configureStoreOptions =>
    {
        // uses the MSI to connect to SQL.
        SqlConnection conn = new SqlConnection(connectionString);
        conn.AccessToken = (new AzureServiceTokenProvider()).
            GetAccessTokenAsync("https://database.windows.net/").Result;

        configureStoreOptions.ConfigureDbContext = builder =>
            builder.UseSqlServer(
                conn,
                sql => sql.MigrationsAssembly(migrationsAssembly));
    })
)

这是堆栈跟踪的一部分:

This is part of the stacktrace:

System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.

非常感谢

Riccardo

推荐答案

你好,



GetAccessTokenAsync返回的访问令牌保证在接下来的5分钟内不会过期。默认情况下,
Azure AD访问令牌会在一小时后到期[1]。



因此,如果您使用相同的令牌(默认过期时间)超过一个小时,您将收到一条"过期令牌"错误消息。请初始化每当您需要使用AdlsClient时,AdlsClient都会从GetAccessTokenAsync获取一个令牌。
GetAccessTokenAsync将访问令牌缓存在内存中,并且如果它在到期后的5分钟内将自动获得新令牌。



懒惰对象总是返回与[2]初始化的对象相同的对象。因此,AdlsClient继续使用旧标记。



参考文献



[1]

https://docs.microsoft.com/en-us/azure/active-directory/active-目录可配置令牌生命周期#token-types





[2]

https://docs.microsoft.com/en-us/dotnet/framework/performance/lazy-initialization#basic-延迟初始化


$

希望这会有所帮助。



问候,

Alberto Morillo

SQLCoffee.com


这篇关于托管标识和SQL连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆