从azure函数创建azure承载令牌

时间:2019-10-02 21:02:01

标签: azure azure-active-directory

我如何才能通过rest API在azure函数内部创建azure承载授权令牌以运行azure VM中的azure运行命令?这些文档没有帮助

1 个答案:

答案 0 :(得分:0)

获取访问令牌非常容易,下面是httpTrigger函数的示例供您参考:

#r "Newtonsoft.Json"
#r "Microsoft.IdentityModel.Clients.ActiveDirectory"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    string AadInstance = "https://login.microsoftonline.com/{0}";
    string ResourceId = "https://management.azure.com/";
    AuthenticationContext authenticationContext = new AuthenticationContext(string.Format(AadInstance, "{tenant}"));
    authenticationContext.ExtendedLifeTimeEnabled = true;
    ClientCredential clientCredential = new ClientCredential("{clientId}", "{clientSecret}");
    AuthenticationResult authticationResult = authenticationContext.AcquireTokenAsync(ResourceId, clientCredential).Result;
    string token=authticationResult.AccessToken;

    return (ActionResult)new OkObjectResult($"bearer token is: {token}");
}

如果您不知道如何获取clientId和clientSecret,可以按照此document在Azure门户上注册该应用程序。