Context.User.Identity.Name is null with SignalR 2.X.X. How to fix it?

23,792

Solution 1

I found the final solution, this is the code of my OWIN startup class:

        public void Configuration(IAppBuilder app)
        {
        app.MapSignalR();

        // Enable the application to use a cookie to store information for the signed i user
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Home/Index")
        });

        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        app.UseMicrosoftAccountAuthentication(new MicrosoftProvider().GetAuthenticationOptions());
        app.UseTwitterAuthentication(new TwitterProvider().GetAuthenticationOptions());
        app.UseFacebookAuthentication(new FacebookProvider().GetAuthenticationOptions());
        app.UseGoogleAuthentication(new GoogleProvider().GetAuthenticationOptions());    
    }

Making myself some coffee, I thought "What about mapping SignalR AFTER the authentication, and voila! Now it's workign as expected.

        public void Configuration(IAppBuilder app)
        {
        // Enable the application to use a cookie to store information for the signed i user
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Home/Index")
        });

        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        app.UseMicrosoftAccountAuthentication(new MicrosoftProvider().GetAuthenticationOptions());
        app.UseTwitterAuthentication(new TwitterProvider().GetAuthenticationOptions());
        app.UseFacebookAuthentication(new FacebookProvider().GetAuthenticationOptions());
        app.UseGoogleAuthentication(new GoogleProvider().GetAuthenticationOptions());

        app.MapSignalR();    
    }

Solution 2

If you're using Web Api and SignalR in the same project, you have to map SignalR before registering Web Api.

Change this:

app.UseWebApi(GlobalConfiguration.Configuration);
app.MapSignalR();

To this:

app.MapSignalR();
app.UseWebApi(GlobalConfiguration.Configuration);

Solution 3

just make sure auth. configuration is called befor start app.MapMignalrR()

i changed this

 public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.MapSignalR();
        ConfigureAuth(app);



    }
}

to this

 public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        app.MapSignalR();


    }
}

hugs ..

Solution 4

If you're mapping /signalr as a 'branched pipeline' you need to do this. Make sure to use bp.UseCookieAuthentication and not app:

app.Map("/signalr", bp =>
{
   bp.UseCookieAuthentication(new CookieAuthenticationOptions
   {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/store/youRaccount/login")
   });

Tip: I deliverately changed the casing so when I see youRaccount in the URL bar I know it worked :-)

Share:
23,792
MRFerocius
Author by

MRFerocius

Updated on July 30, 2021

Comments

  • MRFerocius
    MRFerocius almost 3 years

    This is driving me insane.

    I'm using latest signalR release (2.0.2). This is my hub code (OnConnected)

            public override Task OnConnected()
            {
                //User is null then Identity and Name too.
                Connections.Add(Context.User.Identity.Name, Context.ConnectionId);
                return base.OnConnected();
            }
    

    And this is my Controller's login method:

            [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
            {
                if (ModelState.IsValid)
                {
                  var user = await UnitOfWork.UserRepository.FindAsync(model.UserName,  model.Password);
    
                    if (user != null)
                    {
                        await SignInAsync(user, model.RememberMe);
    
                        return RedirectToLocal(returnUrl);
                    }
                }
    
                TempData["ErrorMessage"] = Resources.InvalidUserNameOrPassword;
    
                // If we got this far, something failed, redisplay form
                return RedirectToAction("Index","Home");
            }
    

    I found that some people are having this issue on OnDisconnected, I don't even make it there.

    I'm using MCV5 template.

    Do you have any idea what is wrong?

  • Ronen Festinger
    Ronen Festinger over 9 years
    man, this is crazy to get to it by your own with no info provided. thanks. in my template it has to be like that: public void Configuration(IAppBuilder app) { ConfigureAuth(app); app.MapSignalR(); }
  • MRFerocius
    MRFerocius over 9 years
    @RonenFestinger I struggled with this like 10 days, no info, when I found it was like solving Fermats last theorem. Crazy :|
  • MRFerocius
    MRFerocius almost 9 years
    This is the answer provided a year and a half.-
  • Josh Noe
    Josh Noe almost 9 years
    @MRFerocius the answer you provided is similar but different. Your answer is to move app.MapSignalR() below Authentication. Mine is to move it above app.UseWebApi(). Someone using both Web Api and SignalR may find this information useful, as it's not intuitive.
  • Chris Woolum
    Chris Woolum over 8 years
    This one did it for me! Thanks!
  • ahmadalibaloch
    ahmadalibaloch almost 8 years
    This did not work for me. I am using OwinContext and OwinContextIdentity.
  • Jonathan
    Jonathan almost 7 years
    Thank you @JoshNoe I spent way too much time on this. This solved my issue.
  • Timur Lemeshko
    Timur Lemeshko over 4 years
    "Making myself some coffee" - was very helpful for me)