SignalR集线器和Identity.Clams

Mil*_*kic 5 c# asp.net asp.net-mvc signalr signalr-hub

我正在使用SignalR从服务器(Asp.net MVC)向客户端发送通知,并且在我的OnConnected()方法中,我用登录名(电子邮件)注册了用户:

public override Task OnConnected()
{
string userName = Context.User.Identity.Name;
string connectionId = Context.ConnectionId;
Groups.Add(connectionId, userName);
return base.OnConnected();
}
Run Code Online (Sandbox Code Playgroud)

现在,我想使用accountId代替名称,然后尝试使用Identity.Claims。在控制器的Login方法中,我创建了新的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;
}
}
Run Code Online (Sandbox Code Playgroud)

我无法使用以下方法在Hub的OnConnected方法内访问我的ClaimsIdentity:

var claim = ((ClaimsIdentity)Context.User.Identity).FindFirst(ClaimTypes.NameIdentifier);
Run Code Online (Sandbox Code Playgroud)

并使用类似的方式。我尝试了许多不同的方法,但是我一直都觉得mvc控制器和Signalr集线器不使用相同的HttpContext,或者有些东西超出了我的主张。我还尝试设置新的身份,例如:

    IPrincipal principal = 
new GenericPrincipal(new GenericIdentity("myuser"), new string[] { "myrole" });
    Thread.CurrentPrincipal = principal;
Run Code Online (Sandbox Code Playgroud)

要么

HttpContext.User = principal;
Run Code Online (Sandbox Code Playgroud)

Ujj*_*pta 5

看看这个——

var identity = (ClaimsIdentity)Context.User.Identity;
var tmp= identity.FindFirst(ClaimTypes.NameIdentifier);
Run Code Online (Sandbox Code Playgroud)