简体   繁体   English

如何获取针对特定用户分配的Azure App Service托管服务标识的令牌?

[英]How to get a token for specific user assigned managed service identity for Azure App Service?

I am trying to get a msi token for a specific User defined identity. 我正在尝试获取特定用户定义身份的msi令牌。 Our app service has 2 user defined identities and I want a token on behalf of one of the user assigned identity. 我们的应用程序服务具有2个用户定义的身份,我想要代表用户分配的身份之一的令牌。

Here is the code: 这是代码:

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(
            "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/&object_id=<ObjectId>&client_id=<clientId>");

        req.Headers["Metadata"] = "true";
        req.Method = "GET";

        try
        {
            // Call /token endpoint
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();

            // Pipe response Stream to a StreamReader, and extract access token
            StreamReader streamResponse = new StreamReader(response.GetResponseStream());
            string stringResponse = streamResponse.ReadToEnd();
            Dictionary<string, string> list =
                 JsonConvert.DeserializeObject<Dictionary<string, string>>(stringResponse);
            string accessToken = list["access_token"];

            System.IO.File.WriteAllText(@".\Log.txt", accessToken);
        }
        catch (Exception e)
        {
            string errorText = String.Format("{0} \n\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : "Acquire token failed");
            System.IO.File.WriteAllText(@".\Log.txt", errorText);
            throw;
        }

It is deployed in an azure app service. 它部署在azure应用程序服务中。 When I hit this section I see this error: An attempt was made to access a socket in a way forbidden by its access permissions 当我点击此部分时,我看到以下错误:尝试以一种其访问权限禁止的方式访问套接字

I tried connecting to http://169.254.169.254 to get the token using kudu console. 我尝试使用Kudu控制台连接到http://169.254.169.254以获取令牌。 But this endpoint does not seem to accessible there. 但是此端点似乎无法访问。

在此处输入图片说明

I did try to use AzureServiceTokenProvider from Microsoft.Azure.Services.AppAuthentication for generating msi token but could not find any documentation about how to use it for multiple user assigned identities. 我确实尝试使用Microsoft.Azure.Services.AppAuthentication中的AzureServiceTokenProvider生成msi令牌,但是找不到有关如何将其用于多个用户分配的身份的任何文档。

Edit: 编辑:

Update 1: 更新1:

I tried to use endpoint from MSI_ENDPOINT environment variable instead of 169.254.169.254. 我尝试从MSI_ENDPOINT环境变量而不是169.254.169.254使用终结点。 But it looks like MSI_ENDPOINT value is not set when I run the app service. 但是,当我运行应用程序服务时,似乎未设置MSI_ENDPOINT值。 Here is the code I have tried: 这是我尝试过的代码:

   var endpoint = Environment.GetEnvironmentVariable("MSI_ENDPOINT");
    string apiVersion = "2018-02-01";
    string resource = "https://management.azure.com/";
    string objectId = "<objectid>";
    string clientId = "<clientId>";

        // Build request to acquire managed identities for Azure resources token
        //HttpWebRequest req = (HttpWebRequest)WebRequest.Create(
        //    "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/&object_id=4aef1720-b3b1-4935-8d68-e330508907fa&client_id=558ecc75-8697-4419-bab9-aa2c87043cfd");

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(
       String.Format(
            "{0}?resource={1}&api-version={2}&object_id={3}&client_id={4}",
            endpoint,
            resource,
            apiVersion,
            objectId,
            clientId));

        req.Headers["Metadata"] = "true";
        req.Method = "GET";

        try
        {
            // Call /token endpoint
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();

            // Pipe response Stream to a StreamReader, and extract access token
            StreamReader streamResponse = new StreamReader(response.GetResponseStream());
            string stringResponse = streamResponse.ReadToEnd();
            Dictionary<string, string> list =
                 JsonConvert.DeserializeObject<Dictionary<string, string>>(stringResponse);
            string accessToken = list["access_token"];

            System.IO.File.WriteAllText(@".\Log.txt", accessToken);
        }
        catch (Exception e)
        {
            string errorText = String.Format("{0} \n\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : "Acquire token failed");

            string log = "MSI_ENDPOINT : " + endpoint + "\n";
            log += ("ErrorText : " + errorText + "\n");
            System.IO.File.WriteAllText(@".\Log.txt", errorText);
            throw;
        }

Firstly, this link How to use managed identities for App Service and Azure Functions provides good documentation specific to MSI for App Services. 首先,此链接如何对App Service和Azure Functions使用托管身份提供了特定于MSI for App Services的良好文档。

Here is quick sample code.. to get token for a specific user assigned managed service identity as you've asked in your question. 这是快速的示例代码..如您所问的那样,获得针对特定用户分配的托管服务标识的令牌。

  • resource - The AAD resource URI of the resource for which a token should be obtained. resource-应为其获取令牌的资源的AAD资源URI。
  • apiversion - The version of the token API to be used. apiversion-要使用的令牌API的版本。 "2017-09-01" is currently the only version supported. 当前仅支持“ 2017-09-01”。
  • clientId - The ID of the user-assigned identity to be used. clientId-要使用的用户分配的身份的ID。 If omitted, the system-assigned identity is used. 如果省略,则使用系统分配的身份。

     public static async Task<HttpResponseMessage> GetToken(string resource, string apiversion, string clientId) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Secret", Environment.GetEnvironmentVariable("MSI_SECRET")); return await client.GetAsync(String.Format("{0}/?resource={1}&api-version={2}&clientid={3}", Environment.GetEnvironmentVariable("MSI_ENDPOINT"), resource, apiversion,clientId)); } 

    Overall I see a few changes that you should notice in the sample code above: 总体而言,我在上面的示例代码中看到了一些应注意的变化:

    1. Make use of MSI_ENDPOINT to construct URL at runtime 利用MSI_ENDPOINT在运行时构造URL
    2. parameter should be clientid and not client_id 参数应该是clientid而不是client_id
    3. parameter object_id is not needed 不需要参数object_id
    4. api version should be "2017-09-01" as documentation in above link says that's the only one supported. api版本应为“ 2017-09-01”,因为以上链接中的文档说这是唯一受支持的版本。
  • About your issue with MSI_ENDPOINT value not being set when you run the app service, please take a look at this note from same link in Microsoft Docs 关于您在运行应用程序服务时未设置MSI_ENDPOINT值的问题,请通过Microsoft Docs中的同一链接查看此说明

    在此处输入图片说明

  • Screenshot from documentation that is relevant for all parameters used 与使用的所有参数相关的文档中的屏幕截图

    在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 具有用户分配的托管标识的 Azure 应用服务使应用程序崩溃 - Azure App Service with User-Assigned Managed Identity crashes application 从 Azure 应用服务连接到 Azure Sql 数据库适用于系统分配但不是用户分配的托管标识 - Connecting from Azure App Service to Azure Sql Database works for System Assigned but not User Assigned managed identity DefaultAzureCredential 不适用于 Azure 应用服务中的用户分配托管标识,而 Azure VMSS 则不然 - DefaultAzureCredential doesn't work with User Assigned Managed Identity in Azure App Service while thats not the case with Azure VMSS Azure 具有用户分配身份的应用服务:在应用中检索 clientId? - Azure App Service with User-assigned identity: retrieve clientId in the app? 在 Linux docker 容器中运行 Asp.Net Core 3.1 的 Azure App Service 是否支持用户分配的托管标识? - Does Azure App Service running Asp.Net Core 3.1 in a Linux docker container support User Assigned Managed Identity? 如何为现有 Azure Service Fabric Cluster 启用用户分配的托管标识并连接到 Azure Key Vault 以读取机密? - How to enable User Assigned Managed Identity to existing Azure Service Fabric Cluster & Connect to Azure Key Vault to read secrets? 对于具有托管身份的Azure应用服务,如何检索客户端ID - For an Azure App service with a managed identity, how to retrieve the Client ID 如何使用 Service Principal/Managed Identity 访问 Azure App Configuration? - How to use Service Principal/Managed Identity to access Azure App Configuration? 使用托管标识在 Azure 中进行应用服务到应用服务的身份验证 - App service to app service auth in Azure using Managed Identity 容器应用服务中缺少 Azure 托管服务标识终结点 - Azure Managed Service Identity endpoint missing in App Service for Containers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM