我使用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;
}
}我不能在集线器中的OnConnected方法中访问我的ClaimsIdentity,使用以下命令:
var claim = ((ClaimsIdentity)Context.User.Identity).FindFirst(ClaimTypes.NameIdentifier);并使用类似的方法。我尝试了许多不同的方法,但我总是觉得mvc控制器和signalr集线器不使用相同的HttpContext,或者有什么东西推翻了我的主张。我也尝试这样设置新的身份:
IPrincipal principal =
new GenericPrincipal(new GenericIdentity("myuser"), new string[] { "myrole" });
Thread.CurrentPrincipal = principal;或
HttpContext.User = principal;发布于 2016-07-29 20:30:49
看看这个-
var identity = (ClaimsIdentity)Context.User.Identity;
var tmp= identity.FindFirst(ClaimTypes.NameIdentifier);发布于 2019-01-26 11:28:07
我也有同样的问题。确保在启动类中调用SignalR之前调用身份验证。
app.UseAuthentication();
app.UseSignalR(routes =>
{
routes.MapHub<MainHub>("/hubs/main");
});https://stackoverflow.com/questions/36502716
复制相似问题