覆盖 HandleAuthenticateAsync 失败原因时丢失 c# .net core 3.1

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

我已经为我的 .net 核心 api 实施了 api 密钥验证,如果发现无效密钥,我 return 按照教程中的说明执行以下操作:

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

这似乎导致我重写了 HandleChallengeAsync 被调用:

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

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

我对将失败原因传递给 .Fail() 调用的目的感到困惑,因为我似乎无法向用户 return 提供它。它有什么用?

我可以从 source 看出 Failure 属性 是一个 Exception:

    public Exception Failure { get; protected set; }


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

由于他们要求 Exception 失败,因此需要一条消息来更新 Exception。我还可以看到一些 logging referencing 这条消息:

    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;
    }