SignInManager IsSignedIn在SignalR hub中返回false

时间:2017-08-14 00:11:33

标签: c# asp.net-core signalr asp.net-identity

我部署了具有SignalR功能的Asp.Net Core应用程序(Gray.microsoft.aspnetcore.signalr.server包),并且想要在Hub类中添加身份授权检查。

public class FooHub : Hub 
{
    private SignInManager<ApplicationUser> SignInManager;
    public FooHub(SignInManager<ApplicationUser> SignInManager)
    {
        this.SignInManager = SignInManager;
    }
    //server method with authorization checking
    public void Method()
    {
        if (!IsAuthorize()) return;
    }

    private bool IsAuthorize()
    {
        return SignInManager.IsSignedIn((ClaimsPrincipal)Context.User);
    }
}
尽管我的用户已获得Identity方案的授权,但

SignInManager.IsSignedIn仍返回false。

在IsSignedIn方法的源代码中,我找到了代码(简化):

return principal.Identities.Any(i => i.AuthenticationType == IdentityConstants.ApplicationScheme);

但Hub.Context.User中有AuthenticationType == null(因此,IsSignedIn返回false)。

我知道在Controller操作中,该字段是从HttpContext实例中挖掘出来的。问题是如何在Hub类中手动设置它以使IsSignedIn返回true?

1 个答案:

答案 0 :(得分:0)

对我来说问题是因为Cookies.ApplicationCookie.AutomaticAuthenticate = false; 即在Startup类中,Identity配置应为

services.Configure<IdentityOptions>(options => { 
    // other configs
    options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
});

因此,当客户端请求Hub方法时,它将使用Identity自动进行身份验证。 SignInManager.IsSignedIn如果成功则返回true