I built a Blazor web app and now I am trying to implement authentication. I created a controller API and I used HttpClient to send requests to the API controller, but for some reason, when I call signInAsync, the cookies expire immediately with the date set to 1 jan 1970, even though I configured the cookie policy in program.cs.
This is how it looks like:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.Cookie.SameSite = SameSiteMode.Strict; options.Cookie.Name = "Test"; options.Cookie.Path = "/"; options.ExpireTimeSpan = TimeSpan.FromDays(1); });This is the controller:
using System.Security.Claims;using Domains.Users;using Interfaces.Users;using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Authentication.Cookies;using Microsoft.AspNetCore.Mvc;namespace Implementations.Controllers;[Route("/api")][ApiController]public class LoginController:ControllerBase{ private readonly IUserService userService; public LoginController(IUserService userService) { this.userService = userService; } [HttpPost] [Route("Login")] public async Task<IActionResult> Login([FromForm] string userEmail , [FromForm] string userPassword) { try { var status = await userService.CheckUserCredentials(userEmail,userPassword); if (status == Domains.Users.User.LoginStatus.allowed) { var userClaims = new[] { new Claim(ClaimTypes.NameIdentifier,Guid.NewGuid().ToString())}; var identity = new ClaimsIdentity(userClaims,CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); var props = new AuthenticationProperties(); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,principal, props); return Ok(); } if (status == Domains.Users.User.LoginStatus.blocked) { return BadRequest("Account not found "); } else if (status == Domains.Users.User.LoginStatus.passwordWrong) { return BadRequest("Please verify your password "); } } catch (Exception e) { return BadRequest("Error while logging in"); } return BadRequest(); }}Finally this is where the HTTP request happens:
private async Task Login(){ var dic = new Dictionary<string, string>() { { "userEmail", userModel.userEmail }, { "userPassword", userModel.userPassword } }; var content = new FormUrlEncodedContent(dic); var response=await _httpClient.PostAsync($"{NavigationManager.BaseUri}api/Login", content).ConfigureAwait(false);}I tried some solution from chat got but to no availanother attempt was adding this
var props = new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddHours(20), IsPersistent = true };in the headers it appears as though it worked and the expiration date / time for the cookie has changed although last expires label (1 jan A970 ) stays the same but the
Response headers:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:{ Date: Sun, 14 Jul 2024 07:25:53 GMT Server: Kestrel Cache-Control: no-cache,no-store Pragma: no-cache Set-Cookie: aze=CfDJ8CfJyZrgmJFNtisBTR-Xg2UBtV3BnF8s0y1WpmkE-JzGLIdYlIvu1m3WUyyD4BAyvLhPJhAO-8TbCXLmK5mUv33yJzWtfcS4yvwqptCPY2Zpky8pmxNRDei_eW8u6_ZILd6F9VhnrGpo1YjgbOSArjlAXdAvpYFFAKUs6_i1fwivm5sgBeZJ4fBinBPz694d5nJhDOkzrHjX23bVnl8ya072M_MNsxd8xIAUAy216VmfvcNVmhURw1sAzleKjCrCsUtzSR1D3X40jRGtEC6U1KDWbC2c5Np64eUckV5qmklbPBlL5lYsAOKOuNj0x2yhtzbftnbNCKSJ9lQgug-bvOMLM5suqKK4gj2KcLJfSvDdKqdiuiVlMgIsqvSgZPORVf2b8Zg38PtUbuETq68rpAAsPYyextXyjfATqzJenIuJ9hGDug-cpNe9fnc5brus-A; expires=Mon, 15 Jul 2024 03:25:52 GMT; path=/; samesite=lax; httponly Content-Length: 0 Expires: Thu, 01 Jan 1970 00:00:00 GMT}, Trailing Headers:{}but when I inspect in the browser I cant find it under the application - cookies section for some reason