我正在使用 SignalR Javascript 客户端和 ASP.NET ServiceHost。我需要 SignalR 集线器和回调只能被登录用户访问。我还需要能够使用来自 HttpContext.Current.User 的 FormsIdentity 从集线器获取当前登录用户的身份。
最佳答案
您应该使用 this.Context.User.Identity
可从 Hub 获得。 See a related question
编辑:要停止未经身份验证的用户:
public void ThisMethodRequiresAuthentication()
{
if(!this.Context.User.Identity.IsAuthenticated)
{
// possible send a message back to the client (and show the result to the user)
this.Clients.SendUnauthenticatedMessage("You don't have the correct permissions for this action.");
return;
}
// user is authenticated continue
}
编辑#2:
这可能会更好,只需返回一条消息
public string ThisMethodRequiresAuthentication()
{
if(!this.Context.User.Identity.IsAuthenticated)
{
// possible send a message back to the client (and show the result to the user)
return "You don't have the correct permissions for this action.");
// EDIT: or throw the 403 exception (like in the answer from Jared Kells (+1 from me for his answer), which I actually like better than the string)
throw new HttpException(403, "Forbidden");
}
// user is authenticated continue
return "success";
}
关于signalr - 保护 SignalR 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9991035/