Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom AuthenticationHandler is called when a method has [AllowAnonymous]

Tags:

c#

asp.net-mvc

I am trying to have my own custom authentication for my server. But it is called for every endpoint even if it has the [AllowAnonymous] attribute on the method. With my current code, I can hit my breakpoint in the HandleAuthenticateAsync method everytime, even on the allow anonymous functions.

The AddCustomAuthentication adds the authenticationhandler correctly

        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddAuthorization();
            services.AddAuthentication(options =>
            {
                // the scheme name has to match the value we're going to use in AuthenticationBuilder.AddScheme(...)
                options.DefaultAuthenticateScheme = "scheme";
                options.DefaultChallengeScheme = "scheme";
            })
            .AddCustomAuthentication(o => { });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();

            app.UseMvc();
        }


...

    public class CustomAuthenticationHandler : AuthenticationHandler<CustomAuthenticationOptions>
    {

        public RvxAuthenticationHandler(
        IOptionsMonitor<RvxAuthenticationOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock) : base(options, logger, encoder, clock)
        {
        }


        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            var token = Request.Headers["token"].ToString();

            if (string.IsNullOrWhiteSpace(token))
            {
                return AuthenticateResult.Fail("Invalid Credentials");
            }


            return AuthenticateResult.Success(new AuthenticationTicket(new System.Security.Claims.ClaimsPrincipal(), "Hi"));
        }
like image 417
Kevin Avatar asked Jul 31 '19 23:07

Kevin


People also ask

What is AuthenticationHandler?

An authentication handler is a class, where we will define how to react to a specific scheme. To implement a handler, we will either have to implement the interface IAuthenticationHandler or derive from class AuthenticationHandler<TOptions> . Inside the handler, we can use our own logic for authenticating a user.

What is AllowAnonymous C#?

One of the new features in ASP.NET MVC 4 is the AllowAnonymous Attribute that helps you secure an entire ASP.NET MVC 4 Website or Controller while providing a convenient means of allowing anonymous users access to certain controller actions, like the login and register Actions.

How to use authentication middleware in. net Core?

Add authentication middlewareAdd the UseAuthentication middleware after UseRouting in the Configure method in the Startup file. This will enable us to authenticate using ASP.NET Core Identity. With all of this in place, the application Is all set to start using Identity.


1 Answers

Add this to the top of your HandleAuthenticateAsync method

protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var endpoint = Context.GetEndpoint();
        if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null)
        {
            return Task.FromResult(AuthenticateResult.NoResult());
        }

        ....
    }

This is what Microsoft use under the covers in the AuthorizeFiler - https://github.com/dotnet/aspnetcore/blob/bd65275148abc9b07a3b59797a88d485341152bf/src/Mvc/Mvc.Core/src/Authorization/AuthorizeFilter.cs#L236

It will allow you to use the AllowAnonymous attribute in controllers to bypass your custom AuthenticationHandler.

like image 155
alexs Avatar answered Sep 30 '22 13:09

alexs