.Net 8 authorization custom response for not authenticated requests #60465
Unanswered
sharpzilla
asked this question in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have a simple cookie-based authentication system and a global fallback authorization handler. How do I handle scenarios where the user hasn't authenticated (e.g., due to an expired or corrupted cookie, or simply failing authentication)?
The framework provides us with
AuthenticateResult
(Microsoft.AspNetCore.Authentication.Cookies.AuthenticateResult), and I need to process this result to return a 401 response code to the frontend along with a custom body DTO. The content of the response body is crucial for the frontend.As far as I understand, when I call httpContext.AuthenticateAsync in the AuthorizationHandler, the authentication process is executed again. However, this seems to be the only way to obtain the authentication result.
I want to achieve a behavior where, if authentication fails, my custom authorization handler is not triggered and specific dto returned.
I also don't understand how to pass Authorization Failure Reason into the Fail method of AuthorizationHandlerContext if the user isn't authenticated. I want to create typed failure reasons, but when the user doesn't pass the authentication policy, the Requirements in GlobalAuthorizationMiddlewareResultHandler is null. Is this possible, or am I doing something wrong?
P.S. My controllers do not have the [Authorize] attribute. I need a behavior where all endpoints in all controllers use the same authentication schema, which is why I'm using a fallback authorization policy.
Program.cs:
ConfigureCookieAuthenticationOptions.cs:
GlobalAuthorizationHandler.cs
GlobalAuthorizationMiddlewareResultHandler.cs
Beta Was this translation helpful? Give feedback.
All reactions