gpt4 book ai didi

c# - 按顺序调用多个 API 来检索和传递 token C#

转载 作者:行者123 更新时间:2023-12-03 02:11:52 26 4
gpt4 key购买 nike

我想利用函数应用程序进行一系列连续的 api 调用,每天将文件下载到存储帐户。我正在利用第一个函数来使用身份验证代码检索刷新 token ,然后添加到正常工作的存储表(也可以使用 key 保管库)(AuthHTTPTrigger)。从现在起,我需要将存储的刷新 token 传递到下一个 api 调用中,以接收访问 token 并更新返回到存储表中的新刷新 token 。下一个 API 调用将传入访问 token 来创建所述报告。此调用现在生成一个 reportId,需要将其与访问 token 一起传递到最后一个 api 调用 url,最终通过安全链接生成报告(本质上将使用计时器来刷新调用,直到 param 不为 null)。

由于每次调用都依赖于前一个调用来传递参数,是否有一种简单的方法可以进行顺序 api 调用?我目前的想法是利用await 任务和await all 以及一个计时器来等待文件的下载链接,为每个api 调用创建另一个函数和单独的任务。

最终,我想手动启动此功能一次,并利用刷新 token ,因为访问 token 每天都会过期,同时每天都会更新刷新 token 。

  1. https://partnercenterxxx.azurewebsites.net/api/AuthHttpTrigger -需要需要手动交互的授权代码 - 生成访问 token 、刷新 token 和 ID token
  2. https://login.windows.net/{app id}/oauth2/token - 传入刷新 token 以提供新的访问 token
  3. https://api.partnercenter.microsoft.com/insights/v1/mpn/ScheduledReport传入访问 token 以创建报告 - 生成报告 ID
  4. https://api.partnercenter.microsoft.com/insights/v1/mpn/ScheduledReport/execution/{reportid} - 传入上次调用的访问 token 并生成报告它
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace PartnerCenterAPI.Properties
{
public static class AuthHttpTrigger
{
[FunctionName("AuthHttpTrigger")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
if (log is null)
{
throw new ArgumentNullException(nameof(log));
}

// Get the authentication code from the request payload
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
string authCode = data.authCode;

// Get the Application details from the settings
string tenantId = Environment.GetEnvironmentVariable("TenantId", EnvironmentVariableTarget.Process);
string clientId = Environment.GetEnvironmentVariable("ClientId", EnvironmentVariableTarget.Process);
string clientSecret = Environment.GetEnvironmentVariable("ClientSecret", EnvironmentVariableTarget.Process);
string storageConnectionString = Environment.GetEnvironmentVariable("TableStorage", EnvironmentVariableTarget.Process);

// Get the access and refresh token from MS Identity
MicrosoftIdentityClient idClient = new(clientId, clientSecret, tenantId);
(string idToken, string accessToken, string refreshToken) = await idClient.GetAccessTokenFromAuthorizationCode(authCode);

// Save the refresh token to an Azure Storage Table
AzureStorageClient azureStorageClient = new(storageConnectionString);
await azureStorageClient.AddOrUpdateRefreshToken(clientId, MicrosoftIdentityClient.GetIdTokenUniqueUser(idToken), refreshToken);

return new OkObjectResult(new ReturnValue
{
AccessToken = accessToken,
IdToken = idToken,
RefreshToken = refreshToken,
});
}
}
}
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace PartnerCenterAPI.Properties
{
public class MicrosoftIdentityClient
{
private static readonly HttpClient httpClient = new();
private static readonly string hostUrl = "https://login.microsoftonline.com";

private readonly string tenantId;
private readonly string clientId;
private readonly string clientSecret;

public MicrosoftIdentityClient(string clientId, string clientSecret, string tenantId)
{
this.clientId = clientId;
this.clientSecret = clientSecret;
this.tenantId = tenantId;
}
public static string GetIdTokenUniqueUser(string idToken)
{
JwtSecurityToken securityToken = new(idToken);
string tid = securityToken.Payload.Claims.FirstOrDefault(claim => claim.Type == "tid").Value;
string sub = securityToken.Payload.Claims.FirstOrDefault(claim => claim.Type == "sub").Value;

return Convert.ToBase64String(Encoding.UTF8.GetBytes($"{tid}{sub}"));
}
public async Task<(string idToken, string accessToken, string refreshToken)> GetAccessTokenFromAuthorizationCode(string authCode)
{
string redirectUrl = "https://partnercenterxxxx.azurewebsites.net";
string scopes = "openid offline_access https://api.partnercenter.microsoft.com/user_impersonation";

Uri requestUri = new($"{hostUrl}/{tenantId}/oauth2/v2.0/token");

List<KeyValuePair<string, string>> content = new()
{
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("scope", scopes),
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("code", authCode),
new KeyValuePair<string, string>("redirect_uri", redirectUrl),
new KeyValuePair<string, string>("client_secret", clientSecret)
};

HttpRequestMessage request = new(HttpMethod.Post, requestUri)
{
Content = new FormUrlEncodedContent(content),
};

HttpResponseMessage response = await httpClient.SendAsync(request);

string responseContent = await response.Content.ReadAsStringAsync();
dynamic responseObject = JsonConvert.DeserializeObject(responseContent);

if (response.IsSuccessStatusCode)
{
// dynamic values need to be assigned before passing back
return (responseObject.id_token, responseObject.access_token, responseObject.refresh_token);
}
else if (response.StatusCode == HttpStatusCode.BadRequest)
{
// Something failed along the way, and there will be an error in there if the error code is 400
// Handle it however you want.
throw new Exception((string)responseObject.error_description);
}
else
{
// ¯\_(ツ)_/¯
throw new Exception("Something bad happened");
}
}
public async Task<(string idToken, string accessToken, string refreshToken)> GetAccessTokenFromRefreshToken(string refreshToken)
{
string scopes = "openid offline_access https://api.partnercenter.microsoft.com/user_impersonation";

Uri requestUri = new($"{hostUrl}/{tenantId}/oauth2/v2.0/token");

List<KeyValuePair<string, string>> content = new()
{
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("scope", scopes),
new KeyValuePair<string, string>("grant_type", "refresh_token"),
new KeyValuePair<string, string>("refresh_token", refreshToken),
new KeyValuePair<string, string>("client_secret", clientSecret)
};

HttpRequestMessage request = new(HttpMethod.Post, requestUri)
{
Content = new FormUrlEncodedContent(content),
};

HttpResponseMessage response = await httpClient.SendAsync(request);

string responseContent = await response.Content.ReadAsStringAsync();
dynamic responseObject = JsonConvert.DeserializeObject(responseContent);

if (response.IsSuccessStatusCode)
{
return (responseObject.id_token, responseObject.access_token, responseObject.refresh_token);
}
else if (response.StatusCode == HttpStatusCode.BadRequest)
{
// Something failed along the way, and there will be an error in there if the error code is 400
// Handle it however you want.
throw new Exception((string)responseObject.error_message);
}
else
{
// ¯\_(ツ)_/¯
throw new Exception("Something bad happened");
}
}
}
}
using Microsoft.Azure.Cosmos.Table;
using System.Threading.Tasks;

namespace PartnerCenterAPI.Properties
{
public class AzureStorageClient
{
private readonly CloudTable refreshTokenTable;

public AzureStorageClient(string connectionString)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());

refreshTokenTable = tableClient.GetTableReference("refreshTokens");
refreshTokenTable.CreateIfNotExists();
}

public async Task<RefreshTokenEntity> AddOrUpdateRefreshToken(string audience, string userId, string refreshToken)
{
RefreshTokenEntity tokenEntity = new(audience, userId)
{
RefreshToken = refreshToken
};

TableResult tableResult = await refreshTokenTable.ExecuteAsync(TableOperation.InsertOrReplace(tokenEntity));

return tableResult.Result as RefreshTokenEntity;
}
}
}
using Microsoft.Azure.Cosmos.Table;
using System;

namespace PartnerCenterAPI.Properties
{
public class RefreshTokenEntity : TableEntity
{

public string RefreshToken { get; set; }

public RefreshTokenEntity(string audience, string userId)
{
RefreshTokenEntity refreshTokenEntity = this;
refreshTokenEntity.PartitionKey = audience;
refreshTokenEntity.RowKey = userId;
}

public static implicit operator string(RefreshTokenEntity v)
{
throw new NotImplementedException();
}
}
}

最佳答案

Create another function and separate tasks for each api call utilizing await task and await all and a timer to await the download link of the file are my current thoughts.

当然,你可以做到。

您还可以使用durable functions .

关于c# - 按顺序调用多个 API 来检索和传递 token C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73111489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com