Implementing Auth0 Authorization for Asp.net Core WebAPI V2

Following the steps mentioned in Auth0 ASP.NET Core Web API SDK Quickstarts: Authorization I am able to add proper Authorization with Auth0.

When we launch the API using .Net Core in IE , it displays a blank page. It would be nice if we can have an appropriate error page displayed.

Testing in PostMan client we can see proper Http Header as 401.
Testing in Chrome displays proper error message. Attaching Chrome and IE Edge screen shots.

We are not able to use the throw error attribute as mentioned in below asp.net core docs when authorization is enabled with Auth0.
Handle errors in ASP.NET Core | Microsoft Learn

GitHub Repo for sample - GitHub - baskarmib/Auth0Samples: Repo for Auth0 Samples

Hi @baskarrao.dandlamudi,

Sorry you are running into issues. I took a look at your repository and think I know what is going on here. You are expecting the app.UseDeveloperExceptionPage(); configuration call in your Startup.cs to show the developer exception page for all routes in the application.

This configuration is intended to be used with endpoints that return UI. Web API is intended to be consumed programmatically, so return html error pages are probably not desired. The “error” you are getting in your browser is an HTTP status code of 401 Unauthorized, which is also expected. You can see the message in your browser’s developer tools.

Your browser then shows the default 401 status code message page for your browser. If you would rather have a text based representation of the status code displayed, you can change your configuration like this:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                /* This only works for MVC
                    webapi is intended to be accessed programmatically
                    so it will not render UI by default */ 
                app.UseDeveloperExceptionPage();
            }

            /* This will cause webapi to send back a friendly status
                message for errors */
            app.UseStatusCodePages();
            app.UseAuthentication();
            app.UseMvc();
        }

Ensure that you add app.UseStatusCodePages(); near the top of your middleware pipeline before any other middlewares that handles responses.

For reference, I created a sample project for you that you can use to see all the configuration needed.

https://github.com/NotMyself/web-api-example

Hope that helps.

Bobby

1 Like

Thanks Bobby for the resolution.

1 Like

FWIW, this post seems to layout your options for error handling in .net core.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.