How to force ValidatePrincipal to be called on AuthenticatedUsers even for [AllowAnonymous] actions?

581 Views Asked by At

I am using cookie authentication on a new ASP.NET CORE 3.1 project.

I have a controller action that is used by both guests as well as authenticated users. Because of that, it is decorated with the AllowAnonymous attribute.

The behavior of the action is slightly different if the user is authenticated so I use httpContext.User.Identity.IsAuthenticated to check that out and if true, I then retrieve the principal's claims in order to perform a database update.

The problem that I have is that because the action allow's anonymous, the OnValidatePrincipal event of the cookie authentication scheme is not called to make sure that the current claims are up to date.

This means that even if the httpContext.User.Identity.IsAuthenticated flag is true, I cannot rely on the claims that come with it because they are not validated in this case.

First of all, this seems to me like a problem. Second, does anyone know if there is a way around that ? Some ways to force the OnValidatePrincipal event to be called as soon as the httpContext.User.Identity.IsAuthenticated flag is true no matter if the action requires authorization or not ?

1

There are 1 best solutions below

0
On

You can try creating a dummy controller method that requires authorization and call it when httpContext.User.Identity.IsAuthenticated flag is true.