首页 文章

SignalR ClaimsIdentity Null Bearer令牌

提问于
浏览
1

我在使用connectionIds创建字典后访问userId时遇到了一些问题 . 我目前正在使用OAuthBearer对我的用户进行身份验证并将信息保存到ClaimsIdentity中,如下所示:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        using (AuthRepository _repo = new AuthRepository())
        {

            IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));


            var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                { 
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                { 
                    "userName", context.UserName
                },
                { 
                    "userId", user.Id
                }
            });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
        }

    }

当我在我的启动/我的signalR集线器时,当我尝试使用IRequest.user.identity.name或 HttpContext.Current.User.Identity.GetUserId(); 时,我得到一个空值 .

public string GetUserId(IRequest request)
        {
            var userId = request.User.Identity.Name;
            return userId.ToString();
        }

我'm thinking that something is wrong with my claims because I can' t访问UserId和userName的值 . 如果我在其他地方运行 HttpContext.Current.User.Identity.GetUserId(); ,我可以获得userId .

任何帮助都会非常感激,因为我已经坚持了很长一段时间 .

1 回答

  • 0

    我遇到了同样的问题,尝试用signalR hub方法中的 Context.Request.GetHttpContext() 替换 HttpContext.Current .

    根据MSDN,HubCallerContext返回客户端的上下文 .

相关问题