How to catch WebAPI Core unauthenticated status

Mr Edge 221 Reputation points
2023-05-09T18:01:28.0866667+00:00

I have the below code in my Web Core API

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

My Controller has [Authorize] at the top. When the API runs, if sending a successful bearer token and request, I can retrieve data and if incorrect I can see a 401 status in Postman.

The way it currently works means when I attempt to access data I don’t get a friendly message back, just an empty response but with a 401 status. How could I return a friendly message? I tried debugging but when an unauthenticated attempt nothing is being highlighted where I could check the status and return a friendly message.

I am using Azure AD with client credentials for this API to be authenticated.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,303 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
313 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
20,173 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,056 Reputation points Microsoft Vendor
    2023-05-10T07:07:55.01+00:00

    Hi @Mr Edge

    How to catch WebAPI Core unauthenticated status

    You can try to use the UseStatusCodePages middleware to capture the http response and format the returned error message. Code like this:

    
    app.UseStatusCodePages(async statusCodeContext =>
    {
        switch (statusCodeContext.HttpContext.Response.StatusCode)
        {
            case 401:
                statusCodeContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                await statusCodeContext.HttpContext.Response.WriteAsJsonAsync(new ErrorMessage { httpStatus = 500, Message = "some message" });
    
                ////If you want to return a html page, use the following code:
                //statusCodeContext.HttpContext.Response.ContentType = "text/html"; 
                //await statusCodeContext.HttpContext.Response.WriteAsync("<html lang=\"en\"><body>\r\n");
                //await statusCodeContext.HttpContext.Response.WriteAsync("401 ERROR From API!<br><br>\r\n"); 
                //await statusCodeContext.HttpContext.Response.WriteAsync( "<a href=\"/\">Home</a><br>\r\n");
                //await statusCodeContext.HttpContext.Response.WriteAsync("</body></html>\r\n"); 
                break;
            case 403:
                statusCodeContext.HttpContext.Response.StatusCode = 400;
                await statusCodeContext.HttpContext.Response.WriteAsJsonAsync(new ErrorMessage { httpStatus = 500, Message = "some message" });
                break;
        }
    });
    

    Then, when using Postman to access the endpoint without token, the result as below:

    User's image

    More detail information about using UseStatusCodePages, see Handle errors in ASP.NET Core


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 59,306 Reputation points
    2023-05-09T20:16:51.0933333+00:00

    the 401 error is perfectly clear and can be handled with code. if instead you returned a 200 and message that said not authenticated. the code would have to parse the response looking for the error. this might make sense if api response always includes errors, the calling app needs to process.