1
votes

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?

1

1 Answers

2
votes

EDIT: As Henk Holtermann suggested in the comments, the best way would be to look into the official Blazor Templates with authentication (Create New Project => Blazor App => Create => Change Authentication). If you for some reason must work with HttpContext, work with the example in the link I provided:

The HttpContext should not be used in a Blazor server-side application, as there is usually no HttpContext available in SignalR applications.

A possible workaround is to create Login/Logout razor pages. The razor pages can access the HttpContext, sign in and then redirect to your actual home page. You can find a detailed description here.