简体   繁体   中英

Azure AD authentication in published WebAPI not working

I am trying to add Azure Active Directory authentication to my ASP.NET WebAPI. I followed this tutorial and have configured my tenant and applications in Azure correctly.

Now if I test this locally with a sample desktop client , the authentication works and I can see the authenticated user's claims.

User.Identity.IsAuthenticated = true

However, if I publish my API to Azure (as a Web app), the authentication does not seem to be working anymore, even with the exact same code used to test the API locally... The only this I have to change is the endpoint to my API:

<add key="ApiBaseAddress" value="http://localhost:20105/" />

vs

<add key="ApiBaseAddress" value="https://***.azurewebsites.net/" />

Note that the JWT token passed to the API is exactly the same when testing my API locally and published, as they are authenticating to the same Azure AD and the same user accound.

What could be the source of this problem? Could it be that azure uses https and I am running on http locally? If so, what could I try to fix this issue?

It seems that when publishing to Azure, some of my Azure AD specific config values in my web.config were replaced...

If you Enable Organizational Authentication, you are able to choose an existing AD, but the deployment just added the config values in a different way than I did.

Unchecking this option and taking care of it myself solved the issue

This might be due to the process you follow for publishing your API. If you are publishing from Visual Studio and you are using the "organizational" settings, the publishing logic will create a NEW app in Azure AD for your cloud hosted web API instance and change the audience settings accordingly. As such, you need to match those changes in the logic requesting a token as well - you need to request a token for your API using the same audience as resource identifier or you'll end up getting a token for your localhost based deployment and send it to your cloud instance, which will reject it. You can avoid this by opting out of using the organizational settings when publishing your app to the website - that will keep the audience unchanged and allow you to use tokens against local and cloud instances indifferently.

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