【发布时间】:2016-07-29 21:37:39
【问题描述】:
我使用 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();
}
现在我想使用 accountId 而不是 name,并尝试使用 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;
}
}
我无法在 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;
【问题讨论】:
-
您是否尝试过从
HttpContext.Current.User.Identity而不是 SignalR 公开的HubCallerContext获取声明?
标签: c# asp.net asp.net-mvc signalr signalr-hub