首页 > 解决方案 > 尝试连接到 Azure Web App 的授权错误

问题描述

我有一个在 Azure 中运行的 Web 应用程序。Web 应用程序配置为使用门户内的身份验证/授权刀片中的 Azure AD。我在 Azure AD 中创建了一个新的来宾用户并毫无问题地连接到 Web 应用程序(并且还同意访问配置文件信息)。

我现在正在尝试使用带有以下代码的控制台应用程序访问 Web 应用程序;从 Azure AD 中的应用注册刀片获取的位置clientId和位置。clientSecret

var client = new HttpClient();
var loginuri = $"https://login.microsoftonline.com/{tenantId}/oauth2/token?api-version=1.0";
var content = new FormUrlEncodedContent(new Dictionary<string, string>
{
    ["grant_type"] = "password",
    ["resource"] = clientId,
    ["client_id"] = clientId,
    ["client_secret"] = clientSecret,
    ["username"] = username,
    ["password"] = password,
});

var tokenResponse = client.PostAsync(loginuri, content).Result;
var tokenJson = tokenResponse.Content.ReadAsStringAsync().Result;
var token = JsonConvert.DeserializeObject<AzureTokenResponse>(tokenJson);

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.token_type, token.access_token);
var imgResponse = client.GetAsync("https://<hidden>.azurewebsites.net/images/banner3.svg").Result;
public class AzureTokenResponse
{
    public string token_type { get; set; }
    public string expires_in { get; set; }
    public string access_token { get; set; }
}

从第一个响应中,我得到一个Bearer令牌,其中token.token_type="Bearer"token.access_token=eA1.... 尽管在我的第二个请求中,我得到的只是状态401 (unauthorized)返回。

标签: c#azureauthenticationazure-active-directoryazure-web-app-service

解决方案


api-version=1.0获取令牌时需要删除。


推荐阅读