如何从Azure AD应用程序客户端ID生成令牌?

时间:2018-10-04 17:27:03

标签: c# azure azure-active-directory

我有one application which is register into azure AD. 我有client id with me and secret key is inside the key vault.

  

如何使用控制台应用程序访问该安全的Azure AD注册api?

我猜我need a bearer token for it how to generate it?

我继续搜索,发现下面的代码-

var authority = "https://login.microsoftonline.com/your-aad-tenant-id/oauth2/token";
var context = new AuthenticationContext(authority);
var resource = "https://some-resource-you-want-access-to";

var clientCredentials = new ClientCredential(clientId, clientSecret);

var result = await context.AcquireTokenAsync(resource, clientCredentials);  

1 个答案:

答案 0 :(得分:1)

您可以尝试下面的代码来生成令牌,在我的示例中,我为https://graph.microsoft.com生成令牌。

string graphResourceId = "https://graph.microsoft.com/";
string authority = "https://login.microsoftonline.com/your-aad-tenant-id/oauth2/token";
string tenantId = "your-aad-tenant-id";
string clientId = "your-clientid";
string secret = "your-secret";
authority = String.Format(authority, tenantId);
AuthenticationContext authContext = new AuthenticationContext(authority);
var accessToken = authContext.AcquireTokenAsync(graphResourceId, new ClientCredential(clientId, secret)).Result.AccessToken;

enter image description here

相关问题