I know that this topic might have some duplicated questions here but i'm still confused. I'm having a very weird case with Thread.CurrentPrincipal.Identity and HttpContext.Current.User.Identity.
I have a userIdentity.cs class where i rely on getting the current active user from my token. Originally my app is an MVC app hosted on IIS on 2 seperate Virtual machines. I was using Thread.CurrentPrincipal.Identity to retrieve the current user from the token claims, and i didn't faced any problems. However, I've update the code to be compatible with a SPA application built in react. After the update, Thread.CurrentPrincipal.Identity isn't working any more, so i had to do a fallback plan and call HttpContext.Current.User.Identity to retieve the claims. So the user Identity class updated to be as follwing :
public class UserIdentity : IUserIdentity
{
private IIdentity _identity;
public UserIdentity()
{
_identity = null;
_identity = InitializeClaimsIdentity();
}
private ClaimsIdentity InitializeClaimsIdentity()
{
return Thread.CurrentPrincipal?.Identity != null ?
Thread.CurrentPrincipal.Identity as ClaimsIdentity :
HttpContext.Current.User.Identity as ClaimsIdentity; //HttpContext.Current.User.Identity used for Main SPA
}
public string GetUserId()
{
var userId = GetClaimsIdentity().FindFirst("username")?.Value;
userId = string.IsNullOrEmpty(userId) ? GetClaimsIdentity(forceInit: true).FindFirst("username")?.Value : userId;
return userId;
}
public ClaimsIdentity GetClaimsIdentity(bool forceInit = false)
{
if (_identity == null || forceInit)
{
_identity = InitializeClaimsIdentity();
}
return (ClaimsIdentity)_identity;
}
}
This solutions works perfectly on dev enviroments (on MVC and SPA).
However, after deploying this solution to production,MVC hosted on 2 VMs, and with a significant ammout of users at the same time, claims started to be returned in the wrong way. UserIDs got messed up returning wrong data. When debugging it, I wasn't able to reproduce the case. When removing HttpContext.Current.User.Identity as ClaimsIdentity as fallback solution, things works like a charm;
If someone can explain to me the main difference between the Thread.CurrentPrincipal and Current.User it would be great.
Plus,how to correctly implement a solution compatible with the MVC and react SPA app ?
Sorry for the long post, and thank you in advance,