Auth0 Home Blog Docs

Implementing Auth0 Authorization for Asp.net Core WebAPI V2

aspnet-core

#1

Following the steps mentioned in https://auth0.com/docs/quickstart/backend/aspnet-core-webapi 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.
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-2.2

GitHub Repo for sample - https://github.com/baskar3078/Auth0Samples


#4

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.

Hope that helps.

Bobby


#5

Thanks Bobby for the resolution.


#6

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

http://www.binaryintellect.net/articles/17841890-a0a2-4094-aabe-1ae85641609c.aspx


#7

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