問題描述
我在啟用了 Azure AD 身份驗證的 Azure 網站上運行了一個標準 Web API,當在瀏覽器中瀏覽 API 時,我能夠通過瀏覽器登錄并獲得對 API 的訪問權限.
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.
然而,WPF 桌面應用程序在提交請求時收到未經授權響應:
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.
我無權訪問 Azure 帳戶,但我確信 Service AD 應用程序配置正確,允許訪問客戶端 AD 應用程序,就像在備用帳戶(未正確配置)上測試時一樣,AuthenticationContext.AcquireTokenAsync
方法失敗.
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.
我確實注意到 - (時間是當然UTC)AuthenticationResult.ExpiresOn
總是在過去,但看不到延長它的方法,這應該是未來的日期嗎?
I did notice that the - (Time is of course UTC)AuthenticationResult.ExpiresOn
is always in the past but see no way of extending it, should this be a future date?
請求:
GET https://example.azure
websites.net/api/categorisation HTTP/1.1
Authorization: Bearer eyJ0eXAiO...
Host: example.azurewebsites.net
回復:
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.
更新:
我在我有權訪問的 Azure 帳戶中重新創建了環境,但仍然收到未經授權的響應(在瀏覽器中可以正常工作).
I have recreated the environment in an Azure account I have access to and still receive an Unauthorised response (works fine in a browser).
推薦答案
問題似乎與 Azure 網站中的身份驗證/授權"選項有關,啟用后,Web Api 將不接受使用身份驗證標頭的請求.禁用該選項并將 Owin 庫與 Azure AD 一起使用提供了所需的解決方案.
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.
這篇關于Azure AD API 請求 401 未經授權的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!