我有一个在 Azure 中运行的 Web 应用程序。 Web 应用程序配置为使用门户内身份验证/授权边栏选项卡中的 Azure AD。我已在 Azure AD 中创建了一个新的 guest 用户,并毫无问题地连接到 Web 应用程序(并且还同意访问配置文件信息)。
我现在尝试使用带有以下代码的控制台应用程序来访问 Web 应用程序;其中 clientId
和 clientSecret
是从 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/