简体   繁体   中英

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;

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");
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM