Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = "https://example.azurewebsites.net/api/list";
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 AuthenticationContext.AcquireTokenAsync method was failing.

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

Request:

GET https://example.azure
websites.net/api/categorisation HTTP/1.1
Authorization: Bearer eyJ0eXAiO...
Host: example.azurewebsites.net

Response:

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

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

Update:

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

like image 432
Anth12 Avatar asked Jul 08 '16 08:07

Anth12


1 Answers

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.

like image 184
Anth12 Avatar answered Sep 19 '22 11:09

Anth12