在使用函数应用的托管标识来获取访问令牌的同时,我正在使用默认的 Azure 凭据方法获取访问令牌。我已经成功获取了令牌。但现在我不确定如何对该方法进行单元测试。以下是当前状态:
private async Task RefreshTokenCache()
{
var tokenCredential = new DefaultAzureCredential();
var accessToken = await tokenCredential.GetTokenAsync(
new TokenRequestContext(scopes: new string[] { _config[AppConstants.ADAPIAppId] + "/.default" }) { });
accessTokenCache.Set(AppConstants.AccessToken, accessToken.Token, DateTimeOffset.Now.AddMinutes(55));
}
是否存在类似于httpclientfactory的东西,我可以注入或传递一些连接字符串,以便告诉DefaultAzureCredential不要调用Azure。
更新
我正在添加更多上下文。我正在使用这个函数应用程序中的方法从Azure获取访问令牌,以便将其用于身份验证APIM。因此,在HttpMessageHandler中,我检查如果令牌不存在,则调用Azure并获取令牌。
在Function App中启动。
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient(AppConstants.ReplyService)
//Adding token handler middleware to add authentication related details.
.AddHttpMessageHandler<AccessTokenHandler>();
}
处理程序文件:
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Use the token to make the call.
// other details
request.Headers.Authorization = new AuthenticationHeaderValue(AppConstants.AuthHeader, await GetToken());
return await base.SendAsync(request, cancellationToken);
}
private async Task<string> GetToken(bool needsRefresh = false)
{
if (accessTokenCache.GetCount() == 0 || needsRefresh)
{
var tokenCredential = new DefaultAzureCredential();
var accessToken = await tokenCredential.GetTokenAsync(
new TokenRequestContext(scopes: new string[] { _config["AppId"] + "/.default" }) { });
accessTokenCache.Set("accessToken", accessToken.Token, DateTimeOffset.Now.AddMinutes(55));
}
return accessTokenCache.Get("accessToken")?.ToString() ?? throw new Exception("Unable to Fetch Access Token from Cache");
}
TokenCredential
位于Azure.Core
命名空间下,而不是Microsoft.WindowsAzure.Storage.Auth
。 - basquiatraphaeuTokenCredential
位于Azure.Core
命名空间下,而不是Microsoft.WindowsAzure.Storage.Auth
。 - undefined