This is driving me insane.
I'm using latest signalR release (2.0.2). This is my hub code (OnConnected)
public override Task OnConnected()
{
//User is null then Identity and Name too.
Connections.Add(Context.User.Identity.Name, Context.ConnectionId);
return base.OnConnected();
}
And this is my Controller's login method:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UnitOfWork.UserRepository.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
}
TempData["ErrorMessage"] = Resources.InvalidUserNameOrPassword;
// If we got this far, something failed, redisplay form
return RedirectToAction("Index","Home");
}
I found that some people are having this issue on OnDisconnected, I don't even make it there.
I'm using MCV5 template.
Do you have any idea what is wrong?
.NET Core SignalR only
For the newer .NET Core SignalR the full instructions explain that when using websockets you need to manually pull out the accessToken from the query string. This is easy to miss.
https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-2.2
Basically where you call
AddAuthentication()
you need to addAddJwtBearer()
and then set a handler for theOnMessageReceived
handler.Search for 'OnMessageReceived' in the above link for the code. It's a bit gnarly in the sense that you even have to add this yourself - but that's why it's easy to miss too.
If you're mapping
/signalr
as a 'branched pipeline' you need to do this. Make sure to usebp.UseCookieAuthentication
and notapp
:Tip: I deliverately changed the casing so when I see
youRaccount
in the URL bar I know it worked :-)If you're using Web Api and SignalR in the same project, you have to map SignalR before registering Web Api.
Change this:
To this:
just make sure auth. configuration is called befor start app.MapMignalrR()
i changed this
to this
hugs ..
I found the final solution, this is the code of my OWIN startup class:
Making myself some coffee, I thought "What about mapping SignalR AFTER the authentication, and voila! Now it's workign as expected.