SignalR集线器和Identity.Claims

我使用SignalR从服务器(Asp.net MVC)向客户端发送通知,在我的OnConnected()方法中,我使用登录名(email)注册用户:

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

现在我想使用accountId而不是名称,并使用Identity.Claims来尝试。 在我的登录方法在控制器中,我创建了新的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;
}
}

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

var claim = ((ClaimsIdentity)Context.User.Identity).FindFirst(ClaimTypes.NameIdentifier);

并采用类似的方式。 我尝试了许多不同的方法,但我一直在感觉mvc控制器和信号集线器不使用相同的HttpContext,或者重写我的说法。 我也尝试设置这样的新身份:

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

要么

HttpContext.User = principal;

看看这个 -

var identity = (ClaimsIdentity)Context.User.Identity;
var tmp= identity.FindFirst(ClaimTypes.NameIdentifier);
链接地址: http://www.djcxy.com/p/96183.html

上一篇: SignalR hub and Identity.Claims

下一篇: Calling SignalR hub methods from a different project