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;
看看这个 -
var identity = (ClaimsIdentity)Context.User.Identity;
var tmp= identity.FindFirst(ClaimTypes.NameIdentifier);
链接地址: http://www.djcxy.com/p/96184.html