SignalR ClaimsIdentity无持票人标记
问题描述:
我有一些麻烦访问我的userId后,并与connectionIds创建我的字典。我目前使用OAuthBearer为我的用户的认证和信息保存到ClaimsIdentity,类似如下:SignalR 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();
}
我在想我的声明有些问题,因为我无法访问UserId和userName的值。如果我在其他地方运行HttpContext.Current.User.Identity.GetUserId();
,则可以获取userId。
任何帮助将不胜感激,因为我已经坚持了很长一段时间。
答
我有同样的问题,请尝试在您的signalR集线器方法内用 Context.Request.GetHttpContext()
代替HttpContext.Current
。按照MSDN HubCallerContext返回客户端的上下文。