C# 如何使用ASP.Net应用程序中的用户身份登录azure SQL

C# 如何使用ASP.Net应用程序中的用户身份登录azure SQL,c#,azure,azure-active-directory,openid-connect,azure-sql-managed-instance,C#,Azure,Azure Active Directory,Openid Connect,Azure Sql Managed Instance,我有一个使用Azure AD身份验证的ASP.Net应用程序,无论我想使用loggedin用户身份连接到Azure数据库。“Active Directory Integrated不适用于此方案 当用户使用microsoft登录页登录到我的应用程序时,同一用户应该能够登录数据库(而不是应用程序标识)并执行一些操作。您可以参考以下代码: public async Task<string> GetTokenForApplicationAsync() {

我有一个使用Azure AD身份验证的ASP.Net应用程序,无论我想使用loggedin用户身份连接到Azure数据库。“Active Directory Integrated不适用于此方案


当用户使用microsoft登录页登录到我的应用程序时,同一用户应该能够登录数据库(而不是应用程序标识)并执行一些操作。

您可以参考以下代码:

public async Task<string> GetTokenForApplicationAsync()
        {
            string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
            ClientCredential clientcred = new ClientCredential(Startup.ClientId, Startup.AppKey);

            // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the token cache
            AuthenticationContext authenticationContext = new AuthenticationContext(Startup.AadInstance + tenantID, new ADALTokenCache(signedInUserID));
            AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync("https://database.windows.net/", clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
            return authenticationResult.AccessToken;
        }
公共异步任务GetTokenForApplicationAsync() { 字符串signedInUserID=ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; 字符串tenantID=ClaimsPrincipal.Current.FindFirst(“http://schemas.microsoft.com/identity/claims/tenantid1.价值; 字符串userObjectID=ClaimsPrincipal.Current.FindFirst(“http://schemas.microsoft.com/identity/claims/objectidentifier1.价值; //在不触发任何用户交互的情况下获取图形的令牌(从缓存,通过多资源刷新令牌等) ClientCredential clientcred=新的ClientCredential(Startup.ClientId,Startup.AppKey); //使用保留在令牌缓存中的当前登录用户的令牌缓存初始化AuthenticationContext AuthenticationContext AuthenticationContext=新的AuthenticationContext(Startup.AadInstance+tenantID,新的ADALTokenCache(SignedUserId)); AuthenticationResult AuthenticationResult=等待authenticationContext.AcquireTokenSilentAsync(“https://database.windows.net/,clientcred,新用户标识符(userObjectID,UserIdentifierType.UniqueId)); 返回authenticationResult.AccessToken; }
下面是一个与Azure AD集成并获取访问令牌以调用Microsoft Graph API的示例。只需将GraphResourceId替换为
https://database.windows.net/

如果我想对azure sql使用基于令牌的身份验证,如何基于登录用户为数据库获取令牌。