Skip to content

FallbackPolicy takes precedence over AuthorizeFilters added using Conventions #39930

@moanrose

Description

@moanrose

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

Security policies applied using the MvcOptions.Conventions does not apply if a FallbackPolicy is specified

I want to add a security policy for a controller using MvcOptions.Conventions, if no FallbackPolicy is specified the security policies are evaluated as expected. However if a FallbackPolicy is specified, only that applies.

Expected Behavior

I would expect the AuthorizeFilters added using Conventions to take precedence over the FallbackPolicy

Steps To Reproduce

The following code should be sufficient to reproduce the problem

using Microsoft.AspNetCore.Authentication.Negotiate;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Authorization;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers(options =>
{
    options.Conventions.Add(new AllowAnonymousConvention());
});
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("allowAnonymous", new AuthorizationPolicyBuilder()
        .RequireAssertion(_ => true)
        .Build());
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAssertion(_ => false)
        .Build();
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

[ApiController]
[Route("[controller]")]
public class HelloWorldController : ControllerBase
{
    [HttpGet]
    public string Get()
    {
        return "Hello world";
    }
}

public class AllowAnonymousConvention : IControllerModelConvention
{
    public void Apply(ControllerModel controller)
    {
        if (controller.ControllerType.Equals(typeof(HelloWorldController)))
        {
            controller.Filters.Add(new AuthorizeFilter(new IAuthorizeData[]
            {
                new AuthorizeAttribute("allowAnonymous")
            }));
        }
    }
}

Exceptions (if any)

No response

.NET Version

6.0.101

Anything else?

No response

Metadata

Metadata

Assignees

Labels

DocsThis issue tracks updating documentationarea-authIncludes: Authn, Authz, OAuth, OIDC, Bearerold-area-web-frameworks-do-not-use*DEPRECATED* This label is deprecated in favor of the area-mvc and area-minimal labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions