I'm using SignalR for sending notifications from server (Asp.net MVC) to client, and in my OnConnected() method I've register users with login name (email):
public override Task OnConnected()
{
string userName = Context.User.Identity.Name;
string connectionId = Context.ConnectionId;
Groups.Add(connectionId, userName);
return base.OnConnected();
}
Now I want to use accountId instead of name, and I trying that with Identity.Claims. Inside my Login method in controller I've created new ClaimsIdentity
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model)
{
----
var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.Email), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
identity.AddClaim(new Claim(ClaimTypes.Role, "guest"));
identity.AddClaim(new Claim(ClaimTypes.GivenName, "A Person"));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, validation.AccountId.ToString())); //from db
AuthenticationManager.SignIn(new AuthenticationProperties
{ IsPersistent = true}, identity);
AuthenticationManager.SignIn(identity);
-----
}
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
I can't access my ClaimsIdentity inside my OnConnected method in Hub, using this:
var claim = ((ClaimsIdentity)Context.User.Identity).FindFirst(ClaimTypes.NameIdentifier);
and using similar ways. I try many different ways but I've always have felling that mvc controller and signalr hub don't use same HttpContext, or something override my claims. I also try to set new identity like this:
IPrincipal principal =
new GenericPrincipal(new GenericIdentity("myuser"), new string[] { "myrole" });
Thread.CurrentPrincipal = principal;
or
HttpContext.User = principal;
Check out this-
var identity = (ClaimsIdentity)Context.User.Identity;
var tmp= identity.FindFirst(ClaimTypes.NameIdentifier);
I had the same problem. Make sure you call Authentication before SignalR in your startup class.
app.UseAuthentication();
app.UseSignalR(routes =>
{
routes.MapHub<MainHub>("/hubs/main");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With