Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR hub and Identity.Claims

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;
like image 449
MilosMokic Avatar asked Apr 08 '16 14:04

MilosMokic


2 Answers

Check out this-

var identity = (ClaimsIdentity)Context.User.Identity;
var tmp= identity.FindFirst(ClaimTypes.NameIdentifier);
like image 170
Ujjwal Kumar Gupta Avatar answered Sep 24 '22 08:09

Ujjwal Kumar Gupta


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");
        });
like image 38
Soulfly Avatar answered Sep 24 '22 08:09

Soulfly