Today I encountered a strange issue in an ASP.NET Core Web API application. Although I didn’t had authentication nor authorization configured(or at least that was what I thought) in my application, I still got a security related error when I tried to call any of the API endpoints:
System.InvalidOperationException:NoauthenticationSchemewasspecified,andtherewasnoDefaultForbidSchemefound.ThedefaultschemescanbesetusingeitherAddAuthentication(stringdefaultScheme)orAddAuthentication(Action<AuthenticationOptions>configureOptions).atMicrosoft.AspNetCore.Authentication.AuthenticationService.ForbidAsync(HttpContextcontext,Stringscheme,AuthenticationPropertiesproperties)atMicrosoft.AspNetCore.Mvc.ForbidResult.ExecuteResultAsync(ActionContextcontext)atMicrosoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultAsync>g__Logged|22_0(ResourceInvokerinvoker,IActionResultresult)atMicrosoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvokerinvoker,TasklastTask,Statenext,Scopescope,Objectstate,BooleanisCompleted)atMicrosoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealedcontext)atMicrosoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State&next,Scope&scope,Object&state,Boolean&isCompleted)atMicrosoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()---Endofstacktracefrompreviouslocation---atMicrosoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvokerinvoker,TasklastTask,Statenext,Scopescope,Objectstate,BooleanisCompleted)atMicrosoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvokerinvoker)atMicrosoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvokerinvoker)atMicrosoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpointendpoint,TaskrequestTask,ILoggerlogger)atMicrosoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContextcontext)atSwashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContexthttpContext)atSwashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContexthttpContext,ISwaggerProviderswaggerProvider)atMicrosoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContextcontext)
Here is my middleware configuration:
As you can see no sign of any form of authentication. So what was causing this error?
After taking a second look at my controller implementation I noticed the problem. I was returning a Forbid actionresult.
The ForbidResult will generate a 403 response and searches for a configured authenticationscheme to decide how this 403 response should be handled. (In some cases the 403 response will result in a redirect to a login page). As there was no authenticationscheme configured it resulted in the error message above.
To fix it I decided to use the ProblemDetails response instead.