I am new in .net core so I tried to keep user session after login. My Auth class is responsible to do that when I hit the login request through postman HttpContext accessor works fine and values are saved in the session like Auth.userId = 1 but when I send request to othr endpoints Auth.userId = 0 I don't know how it happen behind that
Here is my Auth Class
public static class Auth
{
private static IHttpContextAccessor _accessor;
public static void SetSessionWrapper(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
public static int UserId => _accessor.HttpContext.Session.GetId("UserId").Value;
public static string Email => _accessor.HttpContext.Session.GetString("Email").ConvertToString();
public static bool IsLogin => _accessor.HttpContext.Session.GetBoolean("IsLogin").ConvertToBool();
public static string OrganizationType => _accessor.HttpContext.Session.GetString("OrganizationType");
public static int OrganizationId => _accessor.HttpContext.Session.GetId("OrganizationId").Value;
}
and after the login here I create User session
public class UserRepository : Repository<User, FundingPlatformContext>, IUserRepository
{
private readonly FundingPlatformContext _context;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly AppSettings _appSettings;
public UserRepository(FundingPlatformContext context, IHttpContextAccessor httpContextAccessor, IOptions<AppSettings> appSettings) : base(context)
{
_context = context;
_httpContextAccessor = httpContextAccessor;
_appSettings = appSettings.Value;
}
public async Task<LoginResponseDto> CreateUserSession(LoginDto loginDto)
{
var currentUser = await GetUserByEmailAndOrganizationKey(loginDto.Email, loginDto.OrganizationKey);
var loginResponse = new LoginResponseDto();
if (currentUser == null || !currentUser.IsActive)
{
loginResponse.Message = "User does not active with this email and organization key";
return loginResponse;
}
if (await CheckFailedLoginCount(currentUser.Id))
{
loginResponse.Message = "You cannot log in because your user has been locked. Please click on Forgot password or Change password.";
currentUser.IsActive = false;
await _context.SaveChangesAsync();
return loginResponse;
}
try
{
string encPwd = EncryptDecryptHelper.Encrypt(loginDto.Password);
var userDetail = await _context.Users.Include(q => q.FpUserRoles).ThenInclude(r => r.Roles).Include(o => o.Organization).FirstOrDefaultAsync(e => e.Email == loginDto.Email && e.Organization.OrganizationKey == loginDto.OrganizationKey && e.PasswordHash == encPwd);
if (userDetail != null)
{
_httpContextAccessor.HttpContext.Session.SetBoolean("IsLogin", true);
_httpContextAccessor.HttpContext.Session.SetId("UserID", userDetail.Id);
_httpContextAccessor.HttpContext.Session.SetString("Email", userDetail.Email);
_httpContextAccessor.HttpContext.Session.SetId("OrganizationId", userDetail.Organization.Id);
_httpContextAccessor.HttpContext.Session.SetString("OrganizationType", userDetail.Organization.OrganizationType);
_httpContextAccessor.HttpContext.Session.SetBoolean("IsActive", true);
// TODO Maybe save whole serialized userobject in session?
loginResponse.Message = "User logged in successfully!";
userDetail.FailedLoginCount = 0;
userDetail.IsActive = true;
await _context.SaveChangesAsync();
return loginResponse;
}
else
{
currentUser.FailedLoginCount += 1;
loginResponse.Message = "Invalid user name or password.";
await _context.SaveChangesAsync();
return loginResponse;
}
}
catch (Exception ex)
{
loginResponse.Message = "Error Occurred: " + ex.Message;
return null;
}
}
}
In Controller Auth.isLogin returns false even it sets to true after login
public async Task<IActionResult> Login(LoginDto loginData)
{
try
{
if (Auth.IsLogin) return Ok("user already login");
var loginResponse = await _unitOfWork.User.CreateUserSession(loginData);
if (loginResponse.Token == null)
{
return Unauthorized(loginResponse);
}
return Ok(loginResponse);
}
catch (Exception ex)
{
return StatusCode(500, new ErrorDto(ex.Message));
}
}
here is the stratup class
public void ConfigureServices(IServiceCollection services)
{
try
{
_log.Info("[ConfigureServices] LogicApi");
var connectionString = Configuration.GetValue<string>("ConnectionStrings:FundingPrograms");
_log.Info("[ConfigureServices] connectionString " + connectionString);
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddHttpContextAccessor();
var serviceProvider = services.BuildServiceProvider();
var accessor = serviceProvider.GetService<IHttpContextAccessor>();
Auth.SetSessionWrapper(accessor);
services.AddDbContext<FundingPlatformContext>(options => options.UseSqlServer(connectionString, x => x.MigrationsAssembly("FundingPlatform.Data")));
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddControllers();
}
catch (Exception x)
{
_log.Error("[ConfigureServices] Failed", x);
}
}