I cannot create functionals for login user(cookie authentication) on Blazor(server side) For simple example create some code:
@using Microsoft.AspNetCore.Http;
@using Microsoft.AspNetCore.Authentication;
@using Microsoft.AspNetCore.Authentication.Cookies;
@using System.Security.Claims;
@inject IHttpContextAccessor _httpContextAccessor
@inject NavigationManager UriHelper
<form class="form-group">
<input class="form-control" @bind="Name" type="text" />
<input class="form-control" @bind="Password" type="password" />
<button type="button" @onclick="@(()=>SbmForm())" class="btn btn-light">Sbm</button>
</form>
@code{
[Parameter]
public string Name { get; set; }
public string Password { get; set; }
public async Task SbmForm()
{
if (!String.IsNullOrEmpty(Name))
{
var claims = new[] { new Claim(ClaimTypes.Name, Name),
new Claim(ClaimTypes.Role, "Admin") };
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
try
{
await _httpContextAccessor.HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity),
new AuthenticationProperties
{
IsPersistent = true
});
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
UriHelper.NavigateTo("/counter");
}
}
}
I get exception "The response headers cannot be modified because the response has already started." on code "await _httpContextAccessor.HttpContext.SignInAsync..." What I need to do?