如何使用代理设置 C# 获取 Msgraph 令牌

时间:2021-03-03 08:50:21

标签: c# azure-active-directory microsoft-graph-api msal azureportal

我正在使用 C# 守护程序服务应用程序从 Azure 门户读取特定用户的日历事件。

现在,下面的代码在我的电脑上运行良好

private async Task<string> **AcquireToken**()
{
AuthenticationResult Tokenresult = null;
app = CreateConfidentialClientApplicationBuilder(); 

string[] scopes = new string[] { $"{ApiUrl}.default" };
            
try
{
    Tokenresult = await app.AcquireTokenForClient(scopes)
        .ExecuteAsync();
    return Tokenresult?.AccessToken;
}
catch (MsalUiRequiredException ex)
{
    utils.logger.logEvents("The application doesn't have sufficient permissions "
     + " Did you declare enough app permissions during app creation?"
     + "- Did the tenant admin grant permissions to the application?");
    utils.logger.logEvents(ex.Message);
}
catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
{
    utils.logger.logEvents("Scope provided is not supported. Invalid scope. The scope has to be of the form https://resourceurl/.default"
        + "Mitigation: change the scope to be as expected");
}
catch(Exception ex)
{
    utils.logger.logEvents("error in AcquireToken " + ex.Message);
}
return string.Empty;

}

但相同的代码在另一台配置了代理设置的 PC 中不起作用(给出超时错误)。

这里我不知道如何配置上面的代码来使用代理服务器才能到达azure门户。 (我用谷歌搜索了很多小时,但没有运气)

所以请告知如何配置“AcquireTokenForClient()”方法以使用代理设置。

非常感谢

1 个答案:

答案 0 :(得分:0)

更高版本的 MSAL 支持使用您自己的 httpClientFactory,请参阅 https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/httpclient,它使您能够配置底层代理设置

如果您有一个经过身份验证的代理,那么您需要小心您的应用程序将提供哪些凭据(因为您可能不想像示例那样对它们进行硬编码)例如,如果应用程序作为本地系统运行,那么这些凭据就是它的凭据将呈现等