401使用AAD对Azure API应用程序进行身份验证时出错
本文关键字:身份验证 出错 应用程序 API 使用 AAD Azure | 更新日期: 2023-09-27 18:27:13
我有一个API应用程序,它可以很好地与网关主机配合使用,现在网关主机已被弃用,我正努力遵循迁移指南。我已经使用2.8.1 SDK重新部署了我的服务,可以使用AAD或Microsoft帐户通过浏览器登录该服务,并使用Swagger测试该服务。但是,我正在尝试让客户端使用ClientId和Secret访问该服务。代码能够从AAD获得访问令牌,但每当我尝试访问其中一个服务资源时,总是会收到401错误。
当我调试服务时,我在日志中看到以下内容:
Microsoft.Azure.AppService.Authentication Verbose: 0 : Received request: GET https://[myService].azurewebsites.net/api/[myResource]
Microsoft.Azure.AppService.Authentication Warning: 0 : JWT validation failed: IDX10214: Audience validation failed. Audiences: 'https://[myService].azurewebsites.net/'. Did not match: validationParameters.ValidAudience: '[AAD ClientId]' or validationParameters.ValidAudiences: 'http://[myService].azurewebsites.net'.
Microsoft.Azure.AppService.Authentication Information: 0 : Sending response: 401.71 Unauthorized
The thread 0x3b00 has exited with code 0 (0x0).
问题似乎是,与请求一起呈现的Audience是https,但validParameters.ValidAudiences集合仅包含http。
我看不到任何配置访问群体的方法,而且在Visual Studio 2015创建应用程序服务时,似乎正在设置基于http的访问群体。是否有手动编辑ValidAudience集合的方法?
作为参考,我的客户代码是:
private static void Main(string[] args)
{
string app_id_url = "https://[myService].azurewebsites.net/";
string authority = "https://login.windows.net/[myDirectory].onmicrosoft.com/";
string clientId = "[AAD ClientId]";
string clientSecret = "[AAD Client Secret]";
string apiBaseUrl = "https://[myService].azurewebsites.net/";
string aadToken = GetTokenForApplication(authority, clientId, clientSecret, app_id_url);
var apiClient = new HttpClient { BaseAddress = new Uri(apiBaseUrl) };
apiClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", aadToken);
var apiResponse = apiClient.GetAsync(apiBaseUrl + @"api/[myResource]").Result;
string apiResponseContent = apiResponse.Content.ReadAsStringAsync().Result;
Console.WriteLine(apiResponseContent);
}
public static string GetTokenForApplication(string authority, string clientId, string clientSecret, string resourceUrl)
{
AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resourceUrl, clientCred);
string token = authenticationResult.AccessToken;
return token;
}
您的问题与有效受众有关。您可能有两种选择:
选项1。尝试获取具有WebAPI客户端ID作为AcquireToken方法"resource"参数的令牌,而不是其Uri。
选项2。如果以前的方法不起作用,则必须使用Azure资源管理器修改应用程序服务API的身份验证设置。导航到web API,在config
节点下找到authSettings
JSON文档,然后修改数组allowedAudiences
(在更改为读/写模式后)以满足您的需求。在您的情况下,您可能需要将http
更改为https
在我的ASP.NET 4.5 Web应用程序中,我发现必须指定有效访问群体以避免引发运行时异常。
public partial class Startup
{
private static string _aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string _tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string _realm = ConfigurationManager.AppSettings["ida:Wtrealm"];
private static string _metadataAddress = string.Format("{0}/{1}/federationmetadata/2007-06/federationmetadata.xml", _aadInstance, _tenant);
private static string _authority = String.Format(CultureInfo.InvariantCulture, _aadInstance, _tenant);
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
Wtrealm = _realm,
MetadataAddress = _metadataAddress,
TokenValidationParameters = new TokenValidationParameters
{
ValidAudiences = new string[] { "spn:" + _realm }
}
}
);
}
}