4

Context.User is null in my hub, and I'm not sure why.

Starup:

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            AuthenticationMode = AuthenticationMode.Passive,
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity =
                    SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(5),
                        regenerateIdentity:
                            (manager, user) =>
                                user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie))
            }
        });
        app.MapSignalR();

        ConfigureWebApi(app);

        app.UseNancy();

Hub:

public class TestHub : Hub
{
    public void Hello()
    {
        Clients.All.hello(DateTime.Now.ToString("F"));
    }
    public void CurrentUser()
    {
        var user = Context.User;
        Clients.Caller.currentUser(user.Identity);
    }
}

CurrentUser method throws an exception because Context.User is null. I am not sure what additional information will be beneficial. I thought I could get this from the current owin context, but I do not see a way to get this. I've tried to make an IAuthorizeHubConnection attribute, but I cannot find a way to get current owin context from the IRquest object. I can just make a new one.

LRFalk01
  • 961
  • 8
  • 17

1 Answers1

5

SignalR has currently no way to trigger on-demand authentication using authentication middleware configured with passive mode (like Web API w/ OWIN can do with its HostAuthenticationFilter/Attribute). Switch to active mode and it should work:

app.UseCookieAuthentication(new CookieAuthenticationOptions {
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    AuthenticationMode = AuthenticationMode.Active,
    Provider = new CookieAuthenticationProvider {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(5),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie)) }
});
Kévin Chalet
  • 39,509
  • 7
  • 121
  • 131