Anth12 Anth12 - 1 year ago 248
C# Question

Azure AD API request 401 Unauthorized

I have a standard Web API running on an Azure website with Azure AD authentication enabled, when browsing to the API in a browser I am able to login via the browser and gain access to the API.

The WPF desktop application however is receiving an Unauthorized response when submitting the request:

var authContext = new AuthenticationContext(authority, new FileCache());
var accessToken = await authContext.AcquireTokenAsync(apiResourceid, clientId, redirectUri,
new PlatformParameters(PromptBehavior.Auto));
// accessToken is valid

var apiUrl = "";
var request = new HttpRequestMessage(HttpMethod.Get, apiUrl);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.AccessToken);
var response = await httpClient.SendAsync(request);

The authentication is successfull and I can see the User info when debugging.

I do not have access to the Azure account but am confident the Service AD application is configured correctly to allow access to the Client AD application as when testing on an alternate account (not configured correctly) the
method was failing.

I did notice that the
is always in the past but see no way of extending it, should this be a future date?
- (Time is of course UTC)


Authorization: Bearer eyJ0eXAiO...


HTTP/1.1 401 Unauthorized
Content-Length: 58
Content-Type: text/html
Server: Microsoft-IIS/8.0
WWW-Authenticate: Bearer realm=""
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=e35f2977dba55e6708887e762940f75c2a0fcb0a9df4e1cbe0d3f10a614c59b8;Path=/;
Date: Fri, 08 Jul 2016 07:51:13 GMT

You do not have permission to view this directory or page.


I have recreated the environment in an Azure account I have access to and still receive an Unauthorised response (works fine in a browser).

Answer Source

The issue appears to be with the "Authentication / Authorization" option in Azure Websites, when enabled the Web Api will not accept requests using the Authentication header. Disabling the option and using the Owin library alongside Azure AD has provided the solution required.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download