我有一个使用 Azure AD 身份验证的 ASP.Net 应用程序,但是我想使用登录用户身份连接到 azure 数据库。“Active Directory Integrated 不适用于这种情况。
当用户使用 microsoft 登录页面登录我的应用程序时,同一个用户应该能够登录(而不是应用程序身份)到数据库并执行一些操作。
我有一个使用 Azure AD 身份验证的 ASP.Net 应用程序,但是我想使用登录用户身份连接到 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;
}
这是一个与 Azure AD 集成并获取用于调用 Microsoft Graph API 的访问令牌的webapp 示例。只需将 GraphResourceId 替换为https://database.windows.net/.