简体   繁体   中英

How do i login to azure SQL using users identity from a ASP.Net application

I have a ASP.Net application that uses Azure AD Authentication, howver i want to connect to the azure database using the loggedin users identity. "Active Directory Integrated is not working for this scenario.

When a user logs into my application using microsoft login page, the same user should be able to login ( not the application identity) to the database and perform some execution.

You can refer the code below:

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;
        }

Here is an webapp sample which integrate with Azure AD and get access token for calling Microsoft Graph API. Just replace the GraphResourceId with https://database.windows.net/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM