Skip to content
This repository was archived by the owner on Dec 13, 2018. It is now read-only.
This repository was archived by the owner on Dec 13, 2018. It is now read-only.

AllowAnonymous is ignored since migrating to ASP.NET Core 2.0 #1488

@ben-foster-cko

Description

@ben-foster-cko

Hi,

Since migrating to ASP.NET Core 2.0 [AllowAnonymous] is being ignored. I am however using a custom security handler so it's possible this is the issue.

Api Key Handler

    public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
    {
        private readonly IAuthenticationService _authenticationService;
        private readonly Serilog.ILogger _logger;

        public ApiKeyAuthenticationHandler(
            IAuthenticationService authenticationService,
            Serilog.ILogger logger, 
            IOptionsMonitor<ApiKeyAuthenticationOptions> options,
            ILoggerFactory loggerFactory, UrlEncoder encoder,
            IDataProtectionProvider dataProtection, 
            ISystemClock clock)
            : base(options, loggerFactory, encoder, clock)
        {
            _authenticationService = authenticationService ?? throw new ArgumentNullException(nameof(authenticationService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            string authorizationHeader = Request.Headers[HeaderNames.Authorization];

            if (string.IsNullOrEmpty(authorizationHeader))
            {
                return AuthenticateResult.NoResult();
            }

            if (!authorizationHeader.StartsWith(Options.AuthenticationScheme + ' ', StringComparison.OrdinalIgnoreCase))
            {
                return AuthenticateResult.NoResult();
            }

            string apiKeyString = authorizationHeader.Substring(Options.AuthenticationScheme.Length).Trim();

            ApiKey apiKey;
            if (!ApiKey.TryParse(apiKeyString, out apiKey))
            {
                return AuthenticateResult.Fail("Malformed API Key");
            }

            using (_logger.TimeOperation("Authenticating using API key"))
            {
                var principal = await _authenticationService.AuthenticateApiKeyAsync(apiKey, Options.AuthenticationScheme);

                if (principal != null)
                {
                    var authenticationTicket
                        = new AuthenticationTicket(principal, Options.AuthenticationScheme);

                    return AuthenticateResult.Success(authenticationTicket);
                }
            }

            return AuthenticateResult.Fail("Invalid API Key");
        }

        protected override Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            Response.StatusCode = 401;
            Response.Headers.Add(HeaderNames.WWWAuthenticate, Options.AuthenticationScheme);
            return Task.CompletedTask;
        }
    }

Startup (relevant sections)

   public class Startup
    {
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services
                .AddAuthentication(options =>
                {
                    options.DefaultScheme = ApiKeyAuthenticationOptions.DefaultSchemeName;
                    options.DefaultChallengeScheme = ApiKeyAuthenticationOptions.DefaultSchemeName;
                })
                .AddApiKey();

            services
                .AddAuthorization()
                .AddAuthorizationPolicyEvaluator()
                .AddMvcCore(options =>
                {
                    // Secure by default
                    var policy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .Build();

                    options.Filters.Add(new AuthorizeFilter(policy));
                });

            return container.GetInstance<IServiceProvider>();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseAuthentication();
            app.UseMvc();
        }
    }

Packages installed

    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.0.0"/>
    <PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.0.0"/>
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.0.0"/>
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Json" Version="2.0.0"/>
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.0.0"/>
    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.0.0"/>
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0"/>
    <PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="2.0.0"/>
    <PackageReference Include="Microsoft.Extensions.Logging" Version="2.0.0"/>
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="2.0.0"/>
    <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.0.0"/>

Am I missing anything?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions