Working on a project, I encountered a situation I couldn’t wrap my head around. The project includes a (rather simple) ASP.NET Web API project which is published to an Azure App Service instance. Up to now, all of the endpoints I was calling I had secured using Azure AD authentication which is a breeze to set-up. But now wanted to make one specific controller available for unauthenticated calls as well. Normally that’s rather simple, you would just add the [AllowAnonymous] attribute to the controller (or specific action) and voila; authentication would not apply to that one. So I did and published this to Azure only to be returned 401 Unauthorized responses. Hmmm.
It took me quite some digging around before I realized what was happening. My application was actually set-up correctly, it was Azure that was getting in the way. When you open up the settings of your Web App in Azure, there’s this Authentication option. You can use this to easily secure your application with Azure AD.
In the screenshot above, note the options for “Action to take when request is not authenticated” (so: anonymous). I had that set to “Log in with Azure Active Directory”.
This setting completely ignores what you do in your application.
You can regard this authentication as a separate layer on top of your application. So even if your app might allow anonymous requests to some controller, this setting will make sure nothing anonymous gets in. So the simple fix is to set it to: Allow request (no action) instead. Do understand that authorization is now in the hands of your web app, so you need to make sure all of your controllers (at least the ones you need secured) have the [Authorize] attribute.