c# - 尝试连接到 Azure Web App 时出现授权错误

标签 c# azure authentication azure-active-directory azure-web-app-service

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

我现在尝试使用带有以下代码的控制台应用程序来访问 Web 应用程序;其中 clientIdclientSecret 是从 Azure AD 中的应用注册边栏选项卡获取的。

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.token_type="Bearer"token.access_token=eA1....尽管在我的第二个请求中,我得到的只是状态 401(未经授权)

最佳答案

获取token时需要删除api-version=1.0

关于c# - 尝试连接到 Azure Web App 时出现授权错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57326875/

相关文章:

c# - Text.Length 无法查找 webElement 的字符串长度

azure - NvidiaGpuDriverLinux 无法在 NC6 实例上安装

ruby-on-rails - "You are already signed in."是否有设计回调?

authentication - Symfony:为什么有些用户检查应该在身份验证后执行?

c# - XmlDocument.Save() 在文档类型声明中插入空方括号

c# - 浏览器编码问题

javascript - 如何在 asp.net gridview 的代码隐藏中对 Eval 函数进行数据绑定(bind)

c# - Azure 存储 Blob Rest Api header

azure - 在 Azure SAS 下允许多个 IP

javascript - React Native + Redux 基本身份验证