I deploy Asp.Net Core app with SignalR functionality (Gray.microsoft.aspnetcore.signalr.server package) and whant to add Identity authorize checking in a Hub class.
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);
}
}
SignInManager.IsSignedIn
returns false despite of my user is authorized with Identity scheme.
In source code of IsSignedIn method I found the code (simplified):
return principal.Identities.Any(i => i.AuthenticationType == IdentityConstants.ApplicationScheme);
However there is AuthenticationType == null
in Hub.Context.User (so, IsSignedIn returns false).
I know in Controller actions this field is mined from HttpContext instance. The question is how can I set it in Hub class manually to IsSignedIn returns true?
For me the issue was because of Cookies.ApplicationCookie.AutomaticAuthenticate = false;
I.e. in Startup class the Identity configuration should be
services.Configure<IdentityOptions>(options => {
// other configs
options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
});
So when client side requests a Hub method it is authenticated with Identity authomatically. SignInManager.IsSignedIn
returns true if it is successfully