When overriding HandleAuthenticateAsync Fail reason is lost c# .net core 3.1

Viewed 1049

I've implemented an api key auth for my .net core api, and if an invalid key is found I return the following as mentioned in a tutorial:

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

This seems to result in my override of HandleChallengeAsync being called:

    protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            Response.StatusCode = 401;
            Response.ContentType = ProblemDetailsContentType;
            var problemDetails = new UnauthorizedProblemDetails();

            await Response.WriteAsync(JsonSerializer.Serialize(problemDetails));
        }

I'm confused of the purpose of passing the fail reason to the .Fail() call, as it doesn't seem available for me to return to the user. What is it for?

1 Answers

I can see that from the source the Failure property is an Exception:

    public Exception Failure { get; protected set; }


    public static AuthenticateResult Fail(string failureMessage)
        => Fail(new Exception(failureMessage));

Since they are requiring an Exception for the failure, a message is required to new up the Exception. I can also see some logging referencing this message:

    public async Task<AuthenticateResult> AuthenticateAsync()
    {
        var target = ResolveTarget(Options.ForwardAuthenticate);
        if (target != null)
        {
            return await Context.AuthenticateAsync(target);
        }

        // Calling Authenticate more than once should always return the original value.
        var result = await HandleAuthenticateOnceAsync();
        if (result?.Failure == null)
        {
            var ticket = result?.Ticket;
            if (ticket?.Principal != null)
            {
                Logger.AuthenticationSchemeAuthenticated(Scheme.Name);
            }
            else
            {
                Logger.AuthenticationSchemeNotAuthenticated(Scheme.Name);
            }
        }
        else
        {
            Logger.AuthenticationSchemeNotAuthenticatedWithFailure(Scheme.Name, result.Failure.Message);
        }
        return result;
    }
Related