简体   繁体   中英

Authentication of a WebAPI with Azure Active Directory

So this has to be a case of me just needing a dope slap:

I've created new test WebAPI applications using Visual Studio (2013 AND 2015) and configured them to use organizational accounts for authentication using the standard project creation dialogs. I've hooked them to both a test Azure Active Directory (AAD) directory on my workplace's azure subscription as well as one in my MSDN azure subscription.

In all cases, when loading the application for the first time, I get an IIS 401.2 response. Okay, fine. I enable anonymous authentication on the project property window. Then when I navigate to a controller that is decorated with the [Authorize] attribute, I get the following:

<Error>
    <Message>Authorization has been denied for this request.</Message>
</Error>

This occurs both locally as well as in a cloud service web role (with the web role URL added to the application URLs).

I know it has to be something simple. I have to have missed something absolutely idiotic but cannot, for the life of me, figure out what it might be.

Does anyone have any thoughts of why I'm not being redirected to the AAD sign-in page?

The behavior ("being redirected to the AAD sign-in page") is what you would expect for a web application such as an ASP.NET MVC web application. However, this behavior doesn't apply to ASP.NET Web API applications. A Web API (REST API) instead expects the client to present the token in the request. If you don't provide one, then the authorization filter rejects the request, which is why you are seeing an HTTP 401 response when you "navigate" to your Web API url.

The Web API project template configures the OWIN middleware for your application to process and validate a JWT token presented by the client. Evidence of this is in the Startup.Auth.cs file in your project.

在此输入图像描述

Therefore, you need to create a client application that authenticates with Azure AD to acquire the token. The client must be registered with Azure AD and given access to your Web API. Then, from the client application you can invoke the Web API using the token issued from Azure AD. For a quick read on this scenario take a look at this MSDN Magazine article . Don't let the date of the article concern you. It still applies for Visual Studio 2013 and 2015, and gives an excellent explanation of how and why this scenario works this way.

Also, for additional scenarios for authenticating and calling Web API's, see the Azure AD Samples on GitHub.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM