我在启用了 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模板网!