I am using asp.net core web api for backend and React for frontend.I use HttpContext for session in api in post method. when i published api, i can get response from postman for HttpContext session. but from my React app HttpContext session is null.
This is my middleware code. where i set session data.
<code> var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
string connectionString = _configuration.GetConnectionString("DefaultConnection");
string serverSelection = null;
// Check if serverSelection is provided in query string
var queryServerSelection = context.Request.Query["serverSelection"].FirstOrDefault();
if (!string.IsNullOrEmpty(queryServerSelection))
{
serverSelection = queryServerSelection;
connectionString = BuildConnectionString(serverSelection);
// Save serverSelection and connection string in session
context.Session.SetString("ServerSelection", serverSelection);
context.Session.SetString("ConnectionString", connectionString);
}
else if (!string.IsNullOrEmpty(token))
{
// Extract serverSelection from JWT token claims
var jwtToken = new JwtSecurityTokenHandler().ReadToken(token) as JwtSecurityToken;
serverSelection = jwtToken?.Claims.FirstOrDefault(claim => claim.Type == "serverSelection")?.Value;
if (!string.IsNullOrEmpty(serverSelection))
{
connectionString = BuildConnectionString(serverSelection);
// Save serverSelection and connection string in session
context.Session.SetString("ServerSelection", serverSelection);
context.Session.SetString("ConnectionString", connectionString);
}
}
else
{
// Retrieve serverSelection and connection string from session or cookies
serverSelection = context.Session.GetString("ServerSelection");
connectionString = context.Session.GetString("ConnectionString") ?? connectionString;
if (string.IsNullOrEmpty(serverSelection) || string.IsNullOrEmpty(connectionString))
{
throw new InvalidOperationException("Server selection or connection string not found in session or cookies.");
}
}
// Store the final connection string in HttpContext.Items for downstream middleware/controllers
context.Items["ConnectionString"] = connectionString;
await _next(context);
</code>
<code> var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
string connectionString = _configuration.GetConnectionString("DefaultConnection");
string serverSelection = null;
// Check if serverSelection is provided in query string
var queryServerSelection = context.Request.Query["serverSelection"].FirstOrDefault();
if (!string.IsNullOrEmpty(queryServerSelection))
{
serverSelection = queryServerSelection;
connectionString = BuildConnectionString(serverSelection);
// Save serverSelection and connection string in session
context.Session.SetString("ServerSelection", serverSelection);
context.Session.SetString("ConnectionString", connectionString);
}
else if (!string.IsNullOrEmpty(token))
{
// Extract serverSelection from JWT token claims
var jwtToken = new JwtSecurityTokenHandler().ReadToken(token) as JwtSecurityToken;
serverSelection = jwtToken?.Claims.FirstOrDefault(claim => claim.Type == "serverSelection")?.Value;
if (!string.IsNullOrEmpty(serverSelection))
{
connectionString = BuildConnectionString(serverSelection);
// Save serverSelection and connection string in session
context.Session.SetString("ServerSelection", serverSelection);
context.Session.SetString("ConnectionString", connectionString);
}
}
else
{
// Retrieve serverSelection and connection string from session or cookies
serverSelection = context.Session.GetString("ServerSelection");
connectionString = context.Session.GetString("ConnectionString") ?? connectionString;
if (string.IsNullOrEmpty(serverSelection) || string.IsNullOrEmpty(connectionString))
{
throw new InvalidOperationException("Server selection or connection string not found in session or cookies.");
}
}
// Store the final connection string in HttpContext.Items for downstream middleware/controllers
context.Items["ConnectionString"] = connectionString;
await _next(context);
</code>
var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
string connectionString = _configuration.GetConnectionString("DefaultConnection");
string serverSelection = null;
// Check if serverSelection is provided in query string
var queryServerSelection = context.Request.Query["serverSelection"].FirstOrDefault();
if (!string.IsNullOrEmpty(queryServerSelection))
{
serverSelection = queryServerSelection;
connectionString = BuildConnectionString(serverSelection);
// Save serverSelection and connection string in session
context.Session.SetString("ServerSelection", serverSelection);
context.Session.SetString("ConnectionString", connectionString);
}
else if (!string.IsNullOrEmpty(token))
{
// Extract serverSelection from JWT token claims
var jwtToken = new JwtSecurityTokenHandler().ReadToken(token) as JwtSecurityToken;
serverSelection = jwtToken?.Claims.FirstOrDefault(claim => claim.Type == "serverSelection")?.Value;
if (!string.IsNullOrEmpty(serverSelection))
{
connectionString = BuildConnectionString(serverSelection);
// Save serverSelection and connection string in session
context.Session.SetString("ServerSelection", serverSelection);
context.Session.SetString("ConnectionString", connectionString);
}
}
else
{
// Retrieve serverSelection and connection string from session or cookies
serverSelection = context.Session.GetString("ServerSelection");
connectionString = context.Session.GetString("ConnectionString") ?? connectionString;
if (string.IsNullOrEmpty(serverSelection) || string.IsNullOrEmpty(connectionString))
{
throw new InvalidOperationException("Server selection or connection string not found in session or cookies.");
}
}
// Store the final connection string in HttpContext.Items for downstream middleware/controllers
context.Items["ConnectionString"] = connectionString;
await _next(context);
This is my login post method where i return session data and get null.
<code> public IActionResult Login([FromBody] LoginRequest loginRequest)
{
var session = _httpContextAccessor.HttpContext?.Session;
return Ok(new { AccessToken = session.GetString("serverSelection") });
</code>
<code> public IActionResult Login([FromBody] LoginRequest loginRequest)
{
var session = _httpContextAccessor.HttpContext?.Session;
return Ok(new { AccessToken = session.GetString("serverSelection") });
</code>
public IActionResult Login([FromBody] LoginRequest loginRequest)
{
var session = _httpContextAccessor.HttpContext?.Session;
return Ok(new { AccessToken = session.GetString("serverSelection") });
please remember, i got response from postmman. but can’t from my react app.
My React App code:
<code>export const userLoginApi = async (username: string, password: string) => {
try {
const response = await fetch(`${api}Auth/Login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include', // Include credentials (cookies) with the request
body: JSON.stringify({ username, password }) // Pass the username and password in the request body
});
console.log('Login response:', response);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: LoginAuth = await response.json();
console.log('Response data:', data); // Log the response data
return data;
} catch (error) {
console.error("Error during login:", error);
throw error;
}
};
</code>
<code>export const userLoginApi = async (username: string, password: string) => {
try {
const response = await fetch(`${api}Auth/Login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include', // Include credentials (cookies) with the request
body: JSON.stringify({ username, password }) // Pass the username and password in the request body
});
console.log('Login response:', response);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: LoginAuth = await response.json();
console.log('Response data:', data); // Log the response data
return data;
} catch (error) {
console.error("Error during login:", error);
throw error;
}
};
</code>
export const userLoginApi = async (username: string, password: string) => {
try {
const response = await fetch(`${api}Auth/Login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include', // Include credentials (cookies) with the request
body: JSON.stringify({ username, password }) // Pass the username and password in the request body
});
console.log('Login response:', response);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: LoginAuth = await response.json();
console.log('Response data:', data); // Log the response data
return data;
} catch (error) {
console.error("Error during login:", error);
throw error;
}
};
Add program.cs code below
<code>var builder = WebApplication.CreateBuilder(args);
// Ensure the configuration is being loaded
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
// Add services to the container.
builder.Services.AddDbContext<JwtContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Dependency Injection
builder.Services.AddCustomServices(builder.Configuration); // All dependency injections are here
builder.Services.AddControllers()
.AddNewtonsoftJson(options => {
options.SerializerSettings.ContractResolver = new CustomContractResolver();
});
builder.Services.AddCors(options => {
options.AddPolicy("AllowSpecificOrigin", policy => {
policy.WithOrigins("http://localhost:5173", "http://192.168.1.205")
.AllowAnyHeader()
.AllowAnyMethod()
.WithMethods("GET", "POST", "PUT", "DELETE")
.SetIsOriginAllowed((host) => true)
.AllowCredentials();
});
});
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => {
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters() {
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
ValidAudience = builder.Configuration["Jwt:Audience"],
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ClockSkew = TimeSpan.Zero,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"] ?? string.Empty))
};
});
builder.Services.AddHttpContextAccessor();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options => {
options.Cookie.Name = ".ERPWebApi.Session";
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.SameSite = SameSiteMode.None; // Ensure SameSite is None for cross-site requests
});
builder.Services.Configure<CookiePolicyOptions>(options => {
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
app.UseSwagger();
app.UseSwaggerUI();
} else {
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors("AllowSpecificOrigin");
app.UseSession();
app.UseCookiePolicy();
app.UseMiddleware<ConnectionStringMiddleware>(); // Register middleware here
app.UseMiddleware<CustomCorsMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.UseIpRateLimiting();
app.Run();
</code>
<code>var builder = WebApplication.CreateBuilder(args);
// Ensure the configuration is being loaded
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
// Add services to the container.
builder.Services.AddDbContext<JwtContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Dependency Injection
builder.Services.AddCustomServices(builder.Configuration); // All dependency injections are here
builder.Services.AddControllers()
.AddNewtonsoftJson(options => {
options.SerializerSettings.ContractResolver = new CustomContractResolver();
});
builder.Services.AddCors(options => {
options.AddPolicy("AllowSpecificOrigin", policy => {
policy.WithOrigins("http://localhost:5173", "http://192.168.1.205")
.AllowAnyHeader()
.AllowAnyMethod()
.WithMethods("GET", "POST", "PUT", "DELETE")
.SetIsOriginAllowed((host) => true)
.AllowCredentials();
});
});
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => {
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters() {
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
ValidAudience = builder.Configuration["Jwt:Audience"],
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ClockSkew = TimeSpan.Zero,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"] ?? string.Empty))
};
});
builder.Services.AddHttpContextAccessor();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options => {
options.Cookie.Name = ".ERPWebApi.Session";
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.SameSite = SameSiteMode.None; // Ensure SameSite is None for cross-site requests
});
builder.Services.Configure<CookiePolicyOptions>(options => {
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
app.UseSwagger();
app.UseSwaggerUI();
} else {
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors("AllowSpecificOrigin");
app.UseSession();
app.UseCookiePolicy();
app.UseMiddleware<ConnectionStringMiddleware>(); // Register middleware here
app.UseMiddleware<CustomCorsMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.UseIpRateLimiting();
app.Run();
</code>
var builder = WebApplication.CreateBuilder(args);
// Ensure the configuration is being loaded
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
// Add services to the container.
builder.Services.AddDbContext<JwtContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Dependency Injection
builder.Services.AddCustomServices(builder.Configuration); // All dependency injections are here
builder.Services.AddControllers()
.AddNewtonsoftJson(options => {
options.SerializerSettings.ContractResolver = new CustomContractResolver();
});
builder.Services.AddCors(options => {
options.AddPolicy("AllowSpecificOrigin", policy => {
policy.WithOrigins("http://localhost:5173", "http://192.168.1.205")
.AllowAnyHeader()
.AllowAnyMethod()
.WithMethods("GET", "POST", "PUT", "DELETE")
.SetIsOriginAllowed((host) => true)
.AllowCredentials();
});
});
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => {
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters() {
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
ValidAudience = builder.Configuration["Jwt:Audience"],
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ClockSkew = TimeSpan.Zero,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"] ?? string.Empty))
};
});
builder.Services.AddHttpContextAccessor();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options => {
options.Cookie.Name = ".ERPWebApi.Session";
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.SameSite = SameSiteMode.None; // Ensure SameSite is None for cross-site requests
});
builder.Services.Configure<CookiePolicyOptions>(options => {
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
app.UseSwagger();
app.UseSwaggerUI();
} else {
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors("AllowSpecificOrigin");
app.UseSession();
app.UseCookiePolicy();
app.UseMiddleware<ConnectionStringMiddleware>(); // Register middleware here
app.UseMiddleware<CustomCorsMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.UseIpRateLimiting();
app.Run();
7