Search code examples
c#asp.net-coreasp.net-core-webapiasp.net-core-2.2

What is the behavior of Authorize attribute with different authentication scheme in action and controller


 [Authorize(AuthenticationSchemes = AuthenticationSchemes.CookieAuthenticationScheme)]
public class MyController : ControllerBase
{


    [HttpPost("ui")]
    [ProducesResponseType(
        (int) HttpStatusCode.Created)]
    public async Task Action1()
    {

    }


    [HttpPost]
    [ProducesResponseType(
        (int)HttpStatusCode.Created)]
    [Authorize(AuthenticationSchemes = AuthenticationSchemes.JwtAuthenticationScheme)]
    public async Task Action2()
    {

    }
}

I have this controller where Action2 has Authorize attribute with different authentication scheme than that in Controller. But when I invoke Action2 with valid cookie authentication but invalid auth token then also Action2 is authorized - I was expecting to get 401/Unauthorized response.

Is this intended behavior?

Using Asp.net core 2.2


Solution

  • Before ASP.NET Core 2.1, all policies would be evaluated individually and they would all need to be satisfied.

    This changed in ASP.NET Core 2.1, stating that this behaviour was unintended. In that release, policies would be combined, so that if at least one is satisfied, the authorization requirement of the request is satisfied as well.

    The team exposed a new property called AllowCombiningAuthorizeFilters on MvcOptions in case people were relying on that behaviour.

    See:

    If you want to revert to the old behaviour, you can use the following in your Startup class:

    app.AddMvc(options =>
    {
        options.AllowCombiningAuthorizeFilters = false;
    });