I am using a custom CookieAuthentication in ASP.NET Core and I have these three methods in my HomeController:
[Authorize]
public class HomeController : Controller
{
public async Task<IActionResult> Index()
{
_logger.LogInformation("Index()");
if (HttpContext.User.Identity.Name != null)
{
_logger.LogInformation(User.Identity.Name);
}
...
}
[HttpGet("getlastdisposal")]
[AllowAnonymous]
public JsonResult GetLastDisposal()
{
_logger.LogInformation("GetLastDisposal()");
if (HttpContext.User.Identity.Name != null)
{
_logger.LogInformation(User.Identity.Name);
}
else
{
_logger.LogInformation("IT IS NULL");
}
...
}
[HttpGet("getchartdata")]
public JsonResult GetChartData()
{
...
}
}
The log I am getting back is this:
...
info: Server.Controllers.HomeController[0]
Index()
info: Server.Controllers.HomeController[0]
admin
...
info: Server.Controllers.HomeController[0]
GetLastDisposal()
info: Server.Controllers.HomeController[0]
IT IS NULL
...
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[12]
AuthenticationScheme: Cookies was challenged.
Looking at this, it seems like HttpContext.User.Identity.Name becomes null after the first successful authorization (before Index()), which makes the authorization before GetChartData() fail. Any ideas as to why this is happening and how I can fix it?
GetLastDisposal:[AllowAnonymous]as well as[Authorize][Authorize]. I get no errors when I set it to[AllowAnonymous]{ credentials: 'same-origin' }in the client code. That does not have to do with React