【问题标题】:SignalR hub and Identity.ClaimsSignalR 集线器和 Identity.Claims
【发布时间】: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


【解决方案1】:

看看这个-

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

【讨论】:

    【解决方案2】:

    我遇到了同样的问题。确保在启动类中的 SignalR 之前调用 Authentication。

            app.UseAuthentication();
    
            app.UseSignalR(routes =>
            {
                routes.MapHub<MainHub>("/hubs/main");
            });
    

    【讨论】:

      猜你喜欢
      • 2022-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多