![](/img/trans.png)
[英]Getting unauthorized (401) when calling App Service API from Azure Static Web App despite being Linked
[英]Getting Unauthorized from from Azure Web API
我使用針對Web API的Visual Studio 2015 Update 3創建了一個基本項目(無需自定義,沒有任何內容),並按照此處的說明將其部署到Azure(免費帳戶)。 然后,我使用以下代碼創建了一個控制台客戶端。
public static async Task<bool> ReadValues()
{
try
{
// Authenticate the user and get a token from Azure AD
//AuthenticationResult authResult = await AuthContext.AcquireTokenSilentAsync(Resource, ClientId);
AuthenticationResult authResult = AuthContext.AcquireToken(Resource, ClientId, RedirectUri);
// Create an HTTP client and add the token to the Authorization header
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
//"Bearer"
authResult.AccessTokenType
, authResult.AccessToken);
// Call the Web API to get the values
var requestUri = new Uri(WebApiUri, "api/values");
Console.WriteLine("Reading values from '{0}'.", requestUri);
HttpResponseMessage httpResponse = await httpClient.GetAsync(requestUri);
Console.WriteLine("HTTP Status Code: '{0}'", httpResponse.StatusCode.ToString());
//Console.WriteLine("HTTP Header: '{0}'", httpClient.DefaultRequestHeaders.Authorization.ToString());
if (httpResponse.IsSuccessStatusCode)
{
//
// Code to do something with the data returned goes here.
//
var s = await httpResponse.Content.ReadAsStringAsync();
Console.WriteLine(s);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(httpResponse.ReasonPhrase);
}
return (httpResponse.IsSuccessStatusCode);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return false;
}
當我在調試中從Visual Studio本地運行WEB API時,它工作正常,但是當我將其部署到Azure時,它返回未授權。 我可能會問到的一些常見問題:
- 我確實收到了有效的承載令牌
- 我已經在Azure AD中為機器人,Web API和客戶端創建了App注冊
- 客戶端和WEB API使用正確的重定向資源uri
- 我用於登錄的帳戶與用於創建Azure帳戶的帳戶相同,並且在域/ AD / API中具有完全特權
在API方面,這是startup.auth.cs的全部內容
using System.Configuration;
using System.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
using WebApi;
[assembly: OwinStartup("default", typeof(Startup))]
namespace WebApi
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters {
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
},
});
}
}
}
我還應該檢查什么?
其他參考
感謝Juunas的幫助,他為我提供了工作副本,因此我能夠縮小范圍。 當我將調試器附加到Web API的Azure實例時,我可以看到Bad Audience的異常。 在嘗試追溯我的步驟時,我發現從Visual Studio進行部署時,我在導致Web.config更改導致問題的方式的設置中選擇了“企業身份驗證”。 沒有選擇該選項,我能夠通過承載令牌訪問API。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.