I am having a web api service and a web client application to access the web api. Both are registered on azure active directory. However, when the web client application tried to access web api, I got :
ReasonPhrase: 'Unauthorized'
WWW-Authenticate: Bearer error=\"invalid_token\", error_description=\"The signature is invalid
Then I checked the token on https://jwt.io/, it indeed showed "invalid signature". However, I have no idea what is wrong here.
Here is how I retrieved the token:
string authority = "https://login.windows.net/tenantid-log-number/oauth2/token";
string clientID = "83adf895-681a-4dd6-9dfb-2a1484dd4188";
string resourceUri = "https://tenant.onmicrosoft.com/webapiservice";
string appKey = "anJxg3N/5dqiHKx+4zwzFB9A6dN5HdqSitdSOpxzVd=";
ClientCredential clientCredential = new ClientCredential(clientID, appKey);
AuthenticationContext ac = new AuthenticationContext(authority);
Task<AuthenticationResult> authResult = ac.AcquireTokenAsync(resourceUri, clientCredential);
return authResult.Result.AccessToken;
Here is how I access web api service:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://webapiservice.azurewebsites.net/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = client.GetAsync("api/values").Result;
Here is how web api service validates the access:
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = true,
ValidAudience = "https://tenant.onmicrosoft.com/webapiservice",
}
});
Anything wrong here?
Thanks
Based on your configuration and code snippets, it look like you're trying to setup a Web API for .Net Core using the Azure AD v1 endpoint.
For .Net Core using the Azure AD v1 endpoint, you should use
UseJwtBearerAuthentication
as follows:For reference, here are some other setups that can be used:
For .Net using the Azure AD v1 endpoint, you should use
UseWindowsAzureActiveDirectoryBearerAuthentication
Here's a snippet from the official .NET Web API sample, sample that showcases how to set this up:
For .Net using the Azure AD v2 endpoint, you should use
UseOAuthBearerAuthentication
as follows:For .Net Core using the Azure AD v2 endpoint, you should use
UseJwtBearerAuthentication
as follows: