Search code examples
c#authenticationasp.net-coresession-cookiesasp.net-core-3.0

Is there a way to get the Auth Cookie data on Anonymous endpoints?


I have this case where I have an anonymous endpoint can work on it's own but if a user have already done authentication with the cookie I need to get from that authenticated cookie session the data about the authenticated user, but as I searched online I haven't found a solution to this and the User.Identity.IsAuthenticated is always false despite the user has the authenticated session cookie but on a Anonymous endpoint it's like being ignored so I can't figure out if the user data in the cookie.

Is there any way to accomplish this?

Example of the needed behaviour:

[HttpGet,AllowAnonymous]
public async Task<IActionResult> GetSomething()
{
    if(User.Identity.IsAuthenticated){
        //Get data from User.Claims and act upon it
    } else {
        //Get data without user logic
    }
}

Solution

  • You still must use the Authorize attribute. The AllowAnonymous attribute serves to still allow access if the user isn't authorized.

    [HttpGet,Authorize,AllowAnonymous]
    public async Task<IActionResult> GetSomething()