简体   繁体   中英

How to return 401 HTTP status when client omits any of enabled authentication schemes in ASP.NET Core?

We use 2 authentication schemes (Bearer, MTLS) in ASP.NET Core application.

When client ignores to send Client Certificate AND Bearer token, the response is 401 which is expect.

When client sends just Client Certificate OR just Bearer token, the authentication passes and request fails farther on authorization with 403 status code.

Is there a way how to make all authentication methods mandatory and return 401 status code when Client Certificate OR Bearer token is missing?

// Authentication and Authorization setup:
IServiceCollection services = . . .
            . . .
services.AddAuthentication(MtlsAuthenticationHandler.AuthenticationScheme)
    .AddMtlsAuthentication()
    .AddJwtBearer(options =>
    {
        . . .
    });
services.AddAuthorization(options =>
{
    options.AddPolicy("RequireMtlsAndBearer", 
        builder => builder.AddAuthenticationSchemes(MtlsAuthenticationHandler.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme)
            .AddRequirements(. . .)
            .AddRequirements(. . .));
});


// Controller:
[HttpGet("v1/endpoint")]
[Authorize("RequireMtlsAndBearer")]  
public async Task<IActionResult> Get()
{
. . .
}

This is a suggestion. You can do this in Configure method of startup class

app.UseStatusCodePagesWithReExecute("/Error", "?status={0}");

and then in HomeContoller:

   [HttpGet("/Error"), HttpPost("/Error")]
    public IActionResult Error([FromQuery] int status)
    {
        string errors1 = "some info";

        if (status == 403)
        {
            return new JsonResult(new { message = "your description", 
            statusCode=401,errors=errors1 });
       }
       else
        {
            return new JsonResult(new { message = "UNDEFINED_ERROR", statusCode = 
            status, errors = errors1 });
        }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM