asp.netauthenticationasp.net-core

ASP.NET Core - getting a message back from AuthenticationHandler


I have implemented a subclass of AuthenticationHandler. It returns AuthenticationResult.Fail("This is why you can't log in");

I would have expected this message to end up in the body, or at least in the HTTP status text, but instead I get a blank 401 response.

Is there any way to provide additional information for failed authentication attempts in ASP.NET core?


Solution

  • For changing the body or Http status, you could try Context.Response.

    Here is a demo code:

    using Microsoft.AspNetCore.Authentication;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Options;
    using System.Text.Encodings.Web;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Http;
    namespace TestIdentity
    {
        public class CustomAuthenticationHandler<TOptions> : AuthenticationHandler<TOptions> where TOptions : AuthenticationSchemeOptions, new()
        {
            public CustomAuthenticationHandler(IOptionsMonitor<TOptions> options
                , ILoggerFactory logger
                , UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
            {
    
            }
            protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
            {
                await Context.Response.WriteAsync("This is why you can't log in");
                return AuthenticateResult.Fail("This is why you can't log in");
            }
        }
    }