I've been trying to create a Cookie-based authentication for the server side of my Blazor Auto application. As of right now, the user enters their details into a login table, the details are then sent to a controller which then uses an Auth service that creates claims and calls the SignInAsync method to create the cookie and give it to the client.
My controller method is:
public async Task<ActionResult<string>> Login(UserDto request){ bool loginStatus = await serverAuthService.LoginAsync(request); if(loginStatus is false) { return BadRequest("Invalid"); } return Ok("Login: " + loginStatus); }And the service method is:
public async Task<bool> LoginAsync(UserDto request){ var user = await context.Users.FirstOrDefaultAsync(u => u.Name == request.Name); if (user is null) { return false; } var claims = new List<Claim> { new Claim(ClaimTypes.Name, user.Name), new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Role, user.Role) }; var identity = new ClaimsIdentity(claims, "MyCookieAuth"); var principal = new ClaimsPrincipal(identity); var authProperties = new AuthenticationProperties { IsPersistent = true, }; await _httpContextAccessor.HttpContext!.SignInAsync("MyCookieAuth", principal, authProperties); return true;}My program.cs file contains a cookie policy given here:
// Add authentication services with cookie schemebuilder.Services.AddAuthentication("MyCookieAuth") .AddCookie("MyCookieAuth", options => { options.Cookie.Name = ".AspnetCore.Cookie"; options.Cookie.HttpOnly = true; options.LoginPath = "/login"; options.ExpireTimeSpan = TimeSpan.FromMinutes(60); });To the best of my knowledge, I'm doing everything right. The logic flow is basically the same as the Microsoft documentation and yet when I run this and test it out, no cookie is ever attached to my client browser.
I've tried involving a custom AuthenticationStateProvider object but honestly that doesn't seem to really be relevant here.
Any suggestions?