I have an Azure Active Directory and in my Web Api I have a piece of code that I can get a token from Azure Graph Api using the Application that I have registered with Azure and a Client Certificate.
Here is the code that I use right now:
public static string AcquireServiceToken()
{
var authority = string.Format(_authority, "common");
var authContext = new AuthenticationContext(authority);
var result = authContext.AcquireToken(_serviceTokenResourceId, new ClientAssertionCertificate(_serviceTokenClientId, GetClientCertificate(_certThumbprint)));
return result.AccessToken;
}
This snippet of code works just fine, now what I need is a more specific token which has logged-in user's context, so basically I need to be able to pass in a username and password and get a Graph token back from Azure.
Any Ideas?
AcquireToken has another overload that takes in a UserCredential object and U assume you could use that (You will need the TenantId of the Active Directory that the users you need to acquire the tokens for)
Your function will look something like this: (Please fill in the _variables with your own application information)
public static string AcquireTokenWithoutUserCredentials(string userName, string password)
{
var authContext = new AuthenticationContext(string.Format(_authority, _userTokenTenantId));
var userCreds = new UserCredential(userName, password);
var result = authContext.AcquireToken(_resourceId, _userTokenClientId, userCreds);
return result.AccessToken;
}
Looking at your code, looks like you have a multi tenant scenario, in which you use "common" as TenatName, which I'm not sure how/if it will work using the code I pasted here but give it a try ...
A web API can access another web API (in this case, the Graph) as the current user by obtaining a new token via the onbehalfof flow. See https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof for an example. The direct use of username and password is not recommended, credentials should never be collected outside of Azure AD own pages, and in this specific case it would not work (or will stop working soon)