Search code examples
asp.net-coresignalrasp.net-identity

SignInManager.PasswordSignInAsync(...) throws "InvalidOperationExeption : Headers are read-only, response has already started."


I'm using Identity to manage the users in my app.

I Have a Hub with a method SignIn(...) to authenticate users. Inside that method I make a call to SignInManager.PasswordSignInAsync(...) But it keeps throwing the following exception:

System.InvalidOperationException : Headers are read-only, response has already started

What is causing that ? Is it because I'm using signalR ? And Is there a way to fix it ?

Here is the code I have on the server for now:

public class AccountHub : Hub
{
    private readonly IConfiguration configuration;
    private readonly UserManager<User> userManager;
    private readonly SignInManager<User> signInManager;

    public AccountHub(
        IConfiguration configuration,
        UserManager<User> userManager,
        SignInManager<User> signInManager)
    {
        this.configuration = configuration;
        this.userManager = userManager;
        this.signInManager = signInManager;
    }

    public async Task<SignInResultDto> SignIn(UserSignInDto user)
    {
        var result = await signInManager.PasswordSignInAsync(user.Email, user.Password, false, false);
        if (!result.Succeeded)
            return new SignInResultDto { Successful = false, Error = "Username and password are invalid."};
        return new SignInResultDto { Successful = true };
    }
}

And on the client (a .Net client) i'm essencially doing this:

hubConnection = new HubConnectionBuilder()
            .WithUrl(this.navigationManager.ToAbsoluteUri("/Account"))
            .AddMessagePackProtocol()
            .Build();
await hubConnection.StartAsync();
var response = await hubConnection.InvokeAsync<SignInResultDto>("SignIn", userSignInData);

Solution

  • So this issue clearly says that SignInManager sets some cookies when it authenticates the user. SignalR apparently doesn't allow to modify the headers of the http connection after the connection is established. Hence the error.