dariogriffo / ApiKeySample

An API Key api authentication/authorization example
82 stars 26 forks source link

AuthenticateResult Custom Message #2

Closed renerlemes closed 23 hours ago

renerlemes commented 1 week ago

When the AuthenticateResult.Fail("Test Message"); return is used, how is it possible to display this message in a personalized way in a response? What is this message that can be reported used for?

I implemented your code in a project I have, and I use more than one type of authentication (JWT and ApiKey), and I created a Middleware to handle when it is not authenticated, but I cannot customize the response.

My code looks like this:

` namespace VamosAlugar.API.Extensions.Middleware { public class AuthorizationMiddleware : IAuthorizationMiddlewareResultHandler { private readonly AuthorizationMiddlewareResultHandler handler = new();

    public async Task HandleAsync(RequestDelegate requestDelegate, HttpContext httpContext, AuthorizationPolicy authorizationPolicy, PolicyAuthorizationResult policyAuthorizationResult)
    {
        if (!policyAuthorizationResult.Succeeded)
        {
            Models.ResponseDefault responseDefault = new(false, new[] { "CUSTOM_MESSAGE_HERE" });

            httpContext.Response.ContentType = "application/json";
            httpContext.Response.StatusCode = 401;

            await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(responseDefault));

            return;
        }

        await handler.HandleAsync(requestDelegate, httpContext, authorizationPolicy, policyAuthorizationResult);
    }
}

} `

Can you help me?

dariogriffo commented 1 week ago

@renerlemes ping me on linkedin and jump into a call

dariogriffo commented 1 week ago

If I understand correctly you wan to change the body. You can do something like in the response in the following SO question https://stackoverflow.com/a/56491114/2370015

1- Create a new middleware and register it before the authentication. 2- Add a callback in the handle that will be executed right before the response is written. 3- That callback executes before the httpresponse is written in the context so you can still modify it. That's what happening with you at the moment, when you catch in the middleware is already too late and asp doesn't allow you to modify it

renerlemes commented 23 hours ago

@dariogriffo Thanks for your attention and even suggest a 1:1. I managed to solve the problem using the response headers to obtain the message. I still haven't been able to understand how to use the message in the AuthenticateResult.Fail method parameter. But I resolved it another way. Thanks