问题描述
我已经使用ASP.net Core 2.1和Azure AD身份验证开发了UI和Web API。两者都已通过Azure App注册进行注册。我在UI中使用以下代码。但是我收到了未经授权的错误。
string AZURE_AD_INSTANE = "https://login.microsoftonline.com/";
string TENANT_ID = "<tenant GUID>";
string CLIENT_ID = "<Client GUID ofWeb API>";
string SECRET = "<Secret created for Web API under Certificates & secrets>";
string RESOURCE = "https://MyOrg.onmicrosoft.com/TestWebAPI"; //Application ID URI set in Expose an API
ClientCredential ClientCredential = new ClientCredential(CLIENT_ID,SECRET);
string authority = String.Format("{0}{1}",AZURE_AD_INSTANE,TENANT_ID);
AuthenticationContext authContext = new AuthenticationContext(authority);
string accesstoken = authContext.AcquiretokenAsync(RESOURCE,ClientCredential).Result.Accesstoken;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",accesstoken);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,"https://localhost:44326/api/values/Get");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer",accesstoken);
HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult();
string status = response.StatusCode.ToString();
StartUp.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd",options));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
我正在获取访问令牌。当我签入jwt.io时,它说“签名已验证”。但是API调用会提供未经授权的响应状态代码。当我检查响应标题时,它的信息为“ {Bearer error =“ invalid_token”,error_description =“受众无效”}“
我已经看到很多与此错误相关的帖子。但没有任何解决方案。所以有人请告诉我解决这个问题的建议。
谢谢。
解决方法
确保https://MyOrg.onmicrosoft.com/TestWebAPI已在您的WebAPI中注册为有效的受众:
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = true,ValidAudiences = new List<string>
{
"https://MyOrg.onmicrosoft.com/TestWebAPI","..."
}
}
};