如何从Azure Graph API获取基于用户的令牌 [英] How to acquire a user based token from Azure Graph API
问题描述
我有一个Azure Active Directory,在我的Web Api中,我有一段代码,可以使用已在Azure中注册的应用程序和客户端证书从Azure Graph Api获取令牌. 这是我现在使用的代码:
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;
}
此代码段工作正常,现在我需要的是具有登录用户上下文的更特定的令牌,因此基本上我需要能够传递用户名和密码并从Azure取回Graph令牌. 有任何想法吗?
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还有另一个重载,它吸收了UserCredential对象,并且U假定您可以使用它(您将需要Active Directory的TenantId,即您需要的用户获取令牌)
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)
您的函数将如下所示:(请在_variables中填写您自己的应用程序信息)
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;
}
查看您的代码,看来您有一个多租户场景,在该场景中,您使用"common"作为TenatName,但我不确定如何/是否可以使用我在此处粘贴的代码来工作,请尝试一下...
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 ...
这篇关于如何从Azure Graph API获取基于用户的令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!