1

I use cookie based authentication on ASP.NET 6.0.0 SPA template.

    this.connection = new HubConnectionBuilder()
      .withUrl(`${setting.baseUrl}/hub/store`)
      .build();
    await this.connection.start();

And I logged in on action controller as below. I skip password verification. This is just example.

        [HttpPost]
        public async Task<ActionResult> Login(LoginModel model)
        {
            

            var user = await userManager.FindByNameAsync(model.Username);

            if (user is null)
            {
                user = new ApplicationUser();

                await userManager.SetUserNameAsync(user, model.PublicKey);
                var createResult = await userManager.CreateAsync(user);

                if (!createResult.Succeeded)
                    return BadRequest(createResult);
            }

            var claims = new List<Claim> { new Claim(ClaimTypes.NameIdentifier, user.Id) };
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                IsPersistent = true,
                ExpiresUtc = DateTime.UtcNow.AddDays(15)
            };

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);

            await storeHub.Clients.User(user.Id).LoggedIn();

            return Ok();
        }

As you can see i push LoggedIn message for logged in user at the end of login process.

I call the endpoint by ajax request and i see that LoggedIn message is not triggered on client side.

But LoggedIn event is really working when i tested it on another authorized endpoint.

I suspect there is something different when it is tried in login process method.

Any help ?

Freshblood
  • 6,285
  • 10
  • 59
  • 96
  • It seems that the reason is SignalR tab using older cookie still after logged in because messages are pushed to client when tab refreshed – Freshblood Dec 24 '21 at 17:52

1 Answers1

0

If you use connectionid, I believe it will work fine.

For this issue, you can follow my steps to troubleshoot.

  1. Set breakponit in this line await storeHub.Clients.User(user.Id).LoggedIn();.

  2. In your Immediate Window, input Context.User.Identity.Name to check the vaule.

  3. And check the value of user.Id .

Related Post

SignalR - Sending a message to a specific user using (IUserIdProvider) NEW 2.0.0

Jason Pan
  • 15,263
  • 1
  • 14
  • 29